106 Commits

Author SHA1 Message Date
egutierrez 11e6e27ad1 fix(auto): fix secret_store.md YAML — returns/error_type/imports format
- returns: [] (was empty string)
- error_type: error_go_core (was empty, required for impure)
- imports: [list] (was string)
- Removed stale id: field (auto-computed from filename)
- Added output: field for params_schema

fn index now clean: 1324 functions, 45 apps

Co-Authored-By: fn-orquestador <noreply@fn-registry.local>
2026-05-22 21:48:21 +02:00
egutierrez a59b12d467 feat(auto): construir iter 1 — add secret_store_cpp_infra registry function
DPAPI Windows + XOR Linux fallback para almacenar credentials sensibles
en SQLite local. Usado por agents_dashboard para cifrar apikeys.
Incluye encrypt/decrypt/is_strong + base64 helpers.

Issue: 0129
Co-Authored-By: fn-constructor <noreply@fn-registry.local>
2026-05-22 21:42:44 +02:00
egutierrez fe4320af89 chore(auto): construir iter 1 — scaffold agents_dashboard + register in CMakeLists
- init_cpp_app_bash_pipelines scaffold:
  projects/element_agents/apps/agents_dashboard/{main.cpp,CMakeLists.txt,app.md}
- git init dentro del sub-repo (apps_subrepo.md regla)
- Registrado en cpp/CMakeLists.txt (add_subdirectory via _AGENTS_DASHBOARD_DIR)

Co-Authored-By: fn-constructor <noreply@fn-registry.local>
2026-05-22 21:37:06 +02:00
egutierrez f71e0f4c9a chore: remove kanban_cpp app
Gitea repo dataforge/kanban_cpp archived (read-only).
Local apps/kanban_cpp/ deleted, CMake subdir registration removed.
registry.db entry + pc_locations row purged (regenerable via fn index +
manual delete since indexer upserts but does not purge orphaned apps).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 21:30:47 +02:00
egutierrez 46b4385331 feat(issues): 0128 agents_and_robots HTTP API + 0129 agents_dashboard C++ ImGui
0128 (backend, blocks 0129): HTTP daemon en cmd/launcher con apikey Bearer auth, SSE pubsub in-memory para status+logs, TLS via Traefik en agents.organic-machine.com, systemd Restart=always. Scope v0.1 lean: list/start/stop/restart/logs SSE. Send-message + config-edit en v0.2.

0129 (frontend): C++ ImGui agents_dashboard en projects/element_agents/apps/. Panels Connection/Agents/Logs/Status. Persistencia local cifrada DPAPI. Depende de 0128.

Ambos issues con dod_evidence_schema completo (9 + 9 items).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 21:11:30 +02:00
egutierrez 580238b32e feat(infra): auto-commit con 8 cambios
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 14:38:16 +02:00
egutierrez ed767360c1 chore: auto-commit (1 archivos)
- cpp/apps/

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 18:17:04 +02:00
egutierrez 5bac05ce13 refactor(commands): merge /autonomous-task → /autopilot v2
Doble entrada confusa (incidente 2026-05-19 piloto 0121b: cwd
mutation por Path B inline causo commit a branch incorrecta).

Cambios:
- .claude/commands/autopilot.md: v2 simplificado. SOLO pre-flight
  DoD check + delegate fn-orquestador. Sin Path A/B/C inline.
  Self-Q&A migrado al orquestador. Cero cwd mutation.
- .claude/commands/autonomous-task.md: DEPRECADO. Sustitucion 1:1.
  Sigue funcionando como debug primitive sin DoD check.
- dev/issues/0123: revision — eliminar /flow run y /fix-flow (absorbidos
  por /autopilot v2). Mantener fn-meta-orquestador + fn-priorizador
  + fn doctor issues/flows. Anadir tarea: dar a fn-orquestador soporte
  task_type=flow.

Preferencia humano: 1 sola entrada autopilot, "modo que entra y sigue".

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 01:52:19 +02:00
egutierrez d0ceea6f3d done(0121b): fn doctor e2e-coverage funcionando — 42.22% coverage actual
task_run task_d285372493cce2e6 converged 1 iter / ~4 min.
PR https://gitea-.../dataforge/fn_registry/pulls/3 mergeado.

Verificado en master:
  total=45 with_checks=19 coverage=42.22%
  21 apps con propuesta lista en dev/proposals_e2e_checks_0121/ esperando aplicacion (0121c).
  5 apps sin propuesta aun (wave 4 pendiente).

Desbloquea: 0121c (apply N PRs add_e2e_check).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 01:48:15 +02:00
dataforge 0f905b78e0 merge(0121b): fn doctor e2e-coverage
task_run task_d285372493cce2e6 converged 1 iter / 4 min. 4/4 acceptance.

functions/infra/audit_e2e_coverage.go + .md + _test.go
types/infra/e2e_coverage_report.md
cmd/fn/doctor.go (subcmd e2e-coverage)

Cierra: dev/issues/0121b-fn-doctor-e2e-coverage.md
2026-05-18 23:47:32 +00:00
egutierrez 5c7ff8d761 feat(0121b): audit_e2e_coverage_go_infra + fn doctor e2e-coverage subcmd
- Crea functions/infra/audit_e2e_coverage.go: AuditE2ECoverage(roots) escanea
  app.md recursivamente, detecta e2e_checks: en frontmatter, retorna
  E2ECoverageReport{total, with_checks, missing, coverage_pct}.
- Crea functions/infra/e2e_coverage_report.go: tipo E2ECoverageReport con
  JSON tags (total, with_checks, missing, coverage_pct).
- Crea types/infra/e2e_coverage_report.md: metadata del tipo para registry.
- Crea functions/infra/audit_e2e_coverage.md: documentacion self-contained
  con Ejemplo, Cuando usarla, Gotchas.
- Crea functions/infra/audit_e2e_coverage_test.go: 3 tests (empty, all-covered,
  partial) — todos pasan.
- Edita cmd/fn/doctor.go: agrega case "e2e-coverage" -> doctorE2ECoverage().
  Output text (tabla tabwriter + lista de apps missing) y --json (E2ECoverageReport).

Acceptance verificado:
  fn doctor e2e-coverage --json -> {total, with_checks, missing, coverage_pct} OK
  fn doctor e2e-coverage        -> tabla text OK
  go test ./functions/infra/... -> 3/3 PASS
  fn show audit_e2e_coverage_go_infra -> indexada OK

task_run: task_d285372493cce2e6 iter 1

Co-authored-by: fn-orquestador <noreply@fn-registry>
2026-05-19 01:45:54 +02:00
egutierrez 138f4b2713 chore: auto-commit (9 archivos)
- .claude/commands/autopilot.md
- dev/proposals_e2e_checks_0121/altsnap_jitter_test.yaml
- dev/proposals_e2e_checks_0121/app_hub_launcher.yaml
- dev/proposals_e2e_checks_0121/element_matrix_chat.yaml
- dev/proposals_e2e_checks_0121/footprint_geo_stack.yaml
- dev/proposals_e2e_checks_0121/metabase_registry.yaml
- dev/proposals_e2e_checks_0121/script_navegador.yaml
- dev/proposals_e2e_checks_0121/services_monitor.yaml
- dev/proposals_e2e_checks_0121/tables_qa.yaml

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 01:41:49 +02:00
egutierrez 25425a5fd6 chore: auto-commit (1 archivos)
- .claude/commands/autopilot.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 01:37:33 +02:00
egutierrez 89441539fa docs(issues): 4 issues de deuda detectada lateral en 0121a
Origen: fn-recopilador design-e2e descubrio 6 bugs durante el design
de propuestas e2e_checks. Agrupados en 4 issues:

- 0124 EPIC dag_engine cleanup (registry.db huerfana + Mantine drift
       + --migrate-only flag — 3 sub-tareas)
- 0125 deploy_server: anadir --db a cmdServe
- 0126 pipeline_launcher: aplicar migracion 003_logs
- 0127 docker_tui: go.work path absoluto rompe portabilidad

Todos relacionados con 0121a. Pueden ser candidatos a /autonomous-task
o /autopilot dependiendo del scope.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 01:36:53 +02:00
egutierrez 1d3d2f43b3 feat(0121a): wave 2 e2e_checks proposals (8 apps) + README updated
8 fn-recopilador design-e2e paralelos:
- services_api      (Go service, schema custom operations.db)
- registry_mcp      (Go stdio MCP, JSON-RPC handshake test)
- sqlite_api        (Go service read-only HTTP, query_endpoint)
- registry_dashboard (C++ ImGui, NO Go+React como yo supuse)
- primitives_gallery (C++ build gate de toda API C++ del registry, 44 .cpp)
- pipeline_launcher (Go TUI bubbletea)
- docker_tui        (Go TUI + go-duckdb)
- fn_match          (subcmd ./fn, hook helper, fuzzy match)

13/26 apps cubiertas. README documenta:
- 6 bugs/drift descubiertos lateral (dag_engine x3, deploy_server,
  pipeline_launcher, docker_tui).
- 3 correcciones de mi prompt (yo asumi stacks incorrectos).
- Hallazgos arquitectonicos (primitives_gallery = build gate C++).

Pendiente wave 3 (13 apps) + 0121b + 0121c.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 00:43:09 +02:00
egutierrez 2effb688b0 feat(0121a): wave 1 e2e_checks proposals (5 apps)
5 fn-recopilador design-e2e paralelos sobre mix de stacks:
- deploy_server (Go service)
- registry_api  (Go service + FTS5)
- shaders_lab   (C++ ImGui)
- auto_metabase (Python CLI)
- dag_engine    (Go scheduler + react/vite frontend)

Total: 24 checks propuestos. Bloques YAML listos para pegar al
frontmatter de cada app.md tras revision humana.

Advertencias laterales en README.md:
- dag_engine: registry.db huerfana + pnpm build roto + falta --migrate-only
- deploy_server: --db flag no expuesto en cmdServe

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 00:32:55 +02:00
egutierrez eb30074792 chore: auto-commit (8 archivos)
- .claude/rules/registry_calls.md
- apps/dag_engine/README.md
- apps/dag_engine/app.md
- docs/capabilities/INDEX.md
- docs/capabilities/systemd.md
- docs/execution_standard.md
- dev/proposals_e2e_checks_0121/
- docs/capabilities/backends.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 00:31:30 +02:00
egutierrez f8efb7d177 split(0121): epic + 3 sub-issues — design/doctor/apply
0121 era scope demasiado grande para 1 orquestador (batch + new function +
new subcmd + N edits). Split:

- 0121a chore: design-e2e batch (Claude orquesta N fn-recopilador paralelos)
- 0121b feature: audit_e2e_coverage + fn doctor e2e-coverage subcmd
       (tipo feature_app_simple, apto /autonomous-task)
- 0121c chore: aplicar propuestas via N /autonomous-task add_e2e_check

Cada hijo tiene Acceptance verificable + tipo orquestador declarado.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 00:22:23 +02:00
egutierrez f428f2c82a done(0120): orquestador piloto verde — PR mergeado en chart_demo
task_run task_b3069559f34415c3 converged en 2 iter / 2m28s.
PR https://gitea-.../dataforge/chart_demo/pulls/1 mergeado a master.

Desbloquea: 0121, 0122, 0123.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 00:20:38 +02:00
egutierrez f36d091704 docs(0120): hallazgos piloto + regla sub-repos/Gitea API en autonomous_loop
Piloto 0120 convergio en 2 iter (2m28s). PR creado en
dataforge/chart_demo/pulls/1 (no en dataforge/fn_registry — sub-repo).

Anadido a autonomous_loop.md:
- Seccion "Sub-repos vs worktree padre": orquestador opera en sub-repo
  cuando issue toca apps/, projects/*/apps/, cpp/apps/ o analysis/.
- Seccion "Gitea API vs gh": gh auth es smoke, real es curl + pass token.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 00:19:30 +02:00
egutierrez 938853d268 fix(0120): R1+R4 del dry-run — check binary_exists + DB path correcto
R1: fn::run_app no parsea argv. Cambio self_test (--self-test inexistente)
por check estructural test -f binary. Detectado por fn-orquestador dry-run.

R4: schema real de task_runs usa task_id (no issue_id) y DB vive en
apps/deploy_server/operations.db (no agent_runner_api).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 22:00:11 +02:00
egutierrez b31ea70771 docs(plan): issues 0120-0123 — mejora workflow subagentes
Plan en 4 olas para cerrar gaps detectados en revision critica:
- 0120 piloto fn-orquestador (chart_demo e2e_checks)
- 0121 cobertura e2e_checks masiva (fn-recopilador batch)
- 0122 fn-revisor + auto-apply ampliado (desbloquea fase 5)
- 0123 /flow run + fn-meta-orquestador + fn-priorizador

Dep-chain: 0120 -> 0121 -> 0122 -> 0123. Cada uno con
Acceptance verificable programaticamente para que /autonomous-task
pueda converger.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 21:41:02 +02:00
egutierrez 2e5c630d38 chore: baseline pre-piloto 0120 — apps_subrepo rule + http/sse hardening
WIP previo al lanzamiento de fn-orquestador piloto.
Commit como baseline para que /autonomous-task 0120 arranque con master limpio.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 21:40:52 +02:00
egutierrez c52846d475 feat(cpp/core): sse_client_cpp_core — SSE client con reconnect + Last-Event-ID
Cliente Server-Sent Events C++ reusable (fn_sse::Client) con background
thread, exponential backoff, Last-Event-ID y stop() que no bloquea.

Implementacion clave: fork+execvp curl directamente (sin /bin/sh wrapper)
para tener el PID real del proceso curl en curl_pid_, lo que permite que
stop() → kill(SIGTERM) → fgets NULL → join() funcione sin bloqueo.

4 tests (Catch2): connect_and_receive_3_events, parse_event_field,
reconnect_on_disconnect, stop_kills_thread. Fixture Python SSE con
/health probe via http_request_cpp_core.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 19:59:50 +02:00
egutierrez b5affae68c merge issue/0119: kanban_cpp issues/flows sync layer 2026-05-18 18:57:11 +02:00
agent 5b4452b9fe feat(0119): kanban_cpp issues/flows sync layer
Closes issue 0119. Implementation lives in the kanban_cpp sub-repo
(apps/kanban_cpp/backend/). See sub-repo commit 0b93a98 for details.

DoD:
- [x] issues_source.go parses frontmatter via yaml.v3
- [x] flows_source.go idem (distinct status->column mapping)
- [x] frontmatter_edit.go atomic PatchFrontmatterField
- [x] GET /api/boards/issues/cards (smoke: 87 cards)
- [x] GET /api/boards/flows/cards (smoke: 9 cards)
- [x] PATCH /api/boards/issues/cards/0119 status=en-curso (mtime change verified)
- [x] POST /api/boards/issues/cards/0119/launch -> 502 with suggestion
- [x] Tests *_test.go: 4 + 3 + 3 + 1 cache cases, all green
- [x] Cache 30s thread-safe (mutex)
- [x] Taxonomy 0103 respected — only canonical statuses accepted on PATCH

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:56:36 +02:00
egutierrez e0f8f3a068 merge issue/0116: skill_tree v2 Launch workflow boton + feature flag legacy_claude_fix 2026-05-18 18:47:36 +02:00
egutierrez b21e7587ad merge issue/0112: kanban_cpp C++ ImGui app + backend Go :8403 (sub-repo apps/kanban_cpp) 2026-05-18 18:47:31 +02:00
Egutierrez d4924f5cab feat(0112): register kanban_cpp app in cpp/CMakeLists.txt + close issue
Adds add_subdirectory block for apps/kanban_cpp (lives in apps/ per issue
0096). The app itself is a sub-repo (gitignored via apps/*/), with its own
git history and master branch initialized.

Six panels reuse registry: http_request_cpp_core, kpi_card_cpp_viz,
sparkline_cpp_viz, agent_runs_timeline_cpp_viz, dod_evidence_panel_cpp_viz.
Backend Go on :8403 (independent operations.db from kanban_web).
2026-05-18 18:46:50 +02:00
agent 853b3c0363 feat(skill_tree): Launch workflow via agent_runner_api + feature flag legacy_claude_fix (issue 0116)
- dev/feature_flags.json: anade 'legacy_claude_fix' (enabled:false,
  issue 0116). Default OFF — el flujo canonico ahora es 'Launch workflow'
  (POST :8486/api/runs); el boton 'Claude fix' legacy (terminal externa +
  claude --dangerously-skip-permissions) solo se renderiza si se activa
  el flag.
- Mueve dev/issues/0116-skill-tree-launch-workflow.md a completed/.

El codigo C++ del boton vive en el sub-repo dataforge/skill_tree
(apps/skill_tree, commit 9ee3be8).
2026-05-18 18:46:25 +02:00
egutierrez f164ef230f merge issue/0118: agent_runs_timeline C++ ImGui + helpers
# Conflicts:
#	cpp/tests/CMakeLists.txt
2026-05-18 18:33:02 +02:00
egutierrez ff255c9a3c merge issue/0117: dod_evidence_panel C++ ImGui + helpers 2026-05-18 18:32:35 +02:00
egutierrez 6c7f60fb6c merge issue/0115: agent_launch_worktree + agent_cleanup_worktree Go fns + capability group agents 2026-05-18 18:32:31 +02:00
egutierrez 75ac96a2d1 docs: cerrar issue 0118 — agent_runs_timeline_cpp_viz registrado
Funcion + helpers + tests + .md indexados.

- cpp/functions/viz/agent_runs_timeline.{h,cpp,md}
- cpp/functions/viz/agent_runs_timeline_helpers.{h,cpp}
- cpp/tests/test_agent_runs_timeline.cpp (17 cases, 53 assertions, PASS)
- cpp/tests/CMakeLists.txt: add_fn_test test_agent_runs_timeline

fn index: 1283 functions (+1).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:31:53 +02:00
egutierrez da56085e74 docs(viz): agent_runs_timeline.md — frontmatter + self-doc
Issue 0118. Frontmatter completo (kind, lang, domain, version, purity,
signature, params, tags=agents/timeline/sse/imgui/viz/panel,
uses_functions=http_request_cpp_core, error_type, tested).

Secciones obligatorias por contrato self-doc:
- ## Ejemplo — wiring concreto con TimelineState g_state + lock + render
- ## Cuando usarla — dashboard cross-app de agentes
- ## Gotchas — SSE stub, ts en segundos, mutex obligatorio, no autoscroll,
  ImGuiSelectableFlags_AllowOverlap (rename desde AllowItemOverlap),
  app chip hex hardcoded, since_ts no determinista en tests

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:31:45 +02:00
egutierrez ecd864f2d3 test(viz): test_agent_runs_timeline — 17 cases / 53 assertions
Issue 0118. Catch2 coverage de los helpers puros:

- passes_filter: filtro vacio, filter por app, app+status combinado, since_ts
- filter_and_sort: orden started_at DESC, combina filtro + sort
- format_duration: running, segundos, minutos, horas, timestamps invertidos
- status_color_token: mapping conocido + fallback neutral
- status_icon_id: no-empty + distinto entre statuses
- app_chip_hex: apps conocidas + fallback gris

Mock fixture de 5 AgentRun mixtos en make_mock().

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:31:37 +02:00
egutierrez a91ef5aace feat(viz): agent_runs_timeline ImGui panel + SSE stub
Issue 0118.

fn_viz::render_agent_runs_timeline(TimelineState&):
- Filtros: multi-select apps, multi-select statuses, Since (days).
- Connection badge (● green / ◐ amber / ○ red) por state.connection_status.
- Tabla 7 cols: status icon | app chip | issue/card | branch | dod badge |
  duration | started. Selectable SpanAllColumns dispara on_select callback.
- Footer: contadores per-status sobre el set completo.

Thread-safe: snapshot bajo runs_mutex al inicio del frame. SSE client
NO implementado — poll_sse_runs() es stub documentado en .md ## Gotchas.
Consumer puede usar http_request_cpp_core para polling fallback contra
GET /api/runs hasta que un endpoint /api/runs/stream estable aparezca.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:31:29 +02:00
egutierrez c2bdc586a4 feat(viz): agent_runs_timeline helpers — pure filter/sort/format
Issue 0118.

Pure helpers in fn_viz::timeline namespace, free of ImGui:
- passes_filter / filter_and_sort  (multi-select app + status + since_ts)
- format_duration  (running | Ns | MmSSs | HhMMm | —)
- status_color_token / status_icon_id  (status → fn_tokens index / TI_*)
- app_chip_hex  (app id → accent hex, fallback gray)

Designed for unit-test isolation. Render layer (separate commit) consumes
these via agent_runs_timeline.h.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:31:17 +02:00
egutierrez 61a46e4b21 docs: cerrar issue 0117 (dod_evidence_panel C++ implementado)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:30:46 +02:00
egutierrez 3633d128aa docs(viz): frontmatter + self-doc para dod_evidence_panel (issue 0117)
Ejemplo lanzable con DodPanelState mock + Cuando usarla (HITL DoD
validation) + Gotchas (screenshot stub, URL no validada, log read
each-frame, callbacks pueden mutar state, frame ImGui activo
requerido). Tag agents para capability group.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:30:37 +02:00
egutierrez 892ff4f789 test(viz): cubrir helpers de dod_evidence_panel (issue 0117)
7 test cases via Catch2: count_status (3 escenarios incl. unknown
status y missing_required), find_evidence (2 lookup positivo/negativo)
y status_icon_id/status_color_token (mapeo de 4+2 keys). Linkamos solo
helpers — sin ImGui ni vendor extra.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:30:30 +02:00
egutierrez 4388b54356 feat(viz): render ImGui dod_evidence_panel (issue 0117)
Panel con header (run_id + counts) + tabla 6-col (status icon / id /
kind / expected / evidence preview / actions). Soporta 4 kinds de
evidence: screenshot (stub textual), log (5-line preview + popup),
url (xdg-open/ShellExecuteA) y cmd (diff expected vs actual).
Botones Validate/Reject invocan callbacks on_validate/on_reject.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:30:23 +02:00
egutierrez b21adb40c9 feat(viz): helpers puros para dod_evidence_panel (issue 0117)
DodItem/DodEvidence/DodPanelState + count_status/find_evidence/
status_icon_id/status_color_token. Sin ImGui — testeable en aislamiento.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:30:16 +02:00
egutierrez 6fd2e9d071 docs: cerrar issue 0115 (worktree launcher Go fn) 2026-05-18 18:24:24 +02:00
egutierrez d9ef4e54f4 docs(capabilities): create 'agents' group + tag audit_dod_schema
New capability group page docs/capabilities/agents.md consolidating:
- agent_launch_worktree_go_infra
- agent_cleanup_worktree_go_infra
- audit_dod_schema_go_infra (added 'agents' tag to its frontmatter)

3 functions = minimum for a capability group page. Adds row to
docs/capabilities/INDEX.md. End-to-end example shows the launch ->
work -> cleanup -> dod-audit cycle that agent_runner_api (0113)
will orchestrate.
2026-05-18 18:24:17 +02:00
egutierrez 2ea9206934 test(infra): agent_launch_worktree + agent_cleanup_worktree
Three tests for launch:
- creates worktree dir + branch off master
- ResetIfExists=true on existing branch+worktree succeeds
- returns Error when required args missing

Two tests for cleanup:
- removes worktree dir and branch after launch
- tolerates missing worktree/branch (cleanup called twice)

Uses initDummyRepo helper with isolated GIT_CONFIG_GLOBAL=/dev/null
so tests do not pick up user's signing/template config. Echo stub
fallback (claude not in PATH) keeps tests hermetic.
2026-05-18 18:24:13 +02:00
egutierrez 355bcac6c7 feat(infra): agent_launch_worktree + agent_cleanup_worktree Go fns
Two Go functions in functions/infra/ for orchestrating headless Claude
agents inside isolated git worktrees:

- AgentLaunchWorktree(cfg): creates worktree off master, spawns
  claude -p in background, redirects stdout/stderr to LogPath. Falls
  back to echo stub when claude binary missing (CI/test friendly).
  ResetIfExists support for re-runs.

- AgentCleanupWorktree(repo, branch, path, pid): SIGTERM with 1s
  grace then SIGKILL, git worktree remove --force, git branch -D.
  Best-effort: only errors when all three steps fail (idempotent
  cleanup-twice).

Promotes inline bash from .claude/skills/parallel-fix-issues/ and
fn-orquestador to first-class registry functions. Closes issue 0115.

Capability group: agents.
2026-05-18 18:24:08 +02:00
egutierrez 4eb4c1cf98 merge issue/0113: agent_runner_api service Go :8486 + agent_runs.db 2026-05-18 18:18:14 +02:00
egutierrez 40aacac590 merge issue/0110: http_request_cpp_core + http_get_json_cpp_core
# Conflicts:
#	cpp/tests/CMakeLists.txt
2026-05-18 18:18:03 +02:00
egutierrez e9bcbecd24 merge issue/0114: DoD evidence schema + fn doctor dod 2026-05-18 18:17:20 +02:00
egutierrez 7eb7b3d0c8 chore: snapshot WIP previo + flow 0008 + 7 sub-issues (0112-0119)
Snapshot de WIP acumulado de sesiones previas antes de merge wave 1
del flow 0008 (kanban_cpp + agent_runner_api + DoD schema).

Incluye:
- dev/flows/0008-kanban-cpp-and-agent-workflows.md
- dev/issues/0112-0119*.md (7 sub-issues)
- WIP previo en cmd/fn/doctor.go, registry/*, modules/, cpp/, etc.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:17:08 +02:00
egutierrez 61ec4c8a76 docs: cerrar issue 0110 (http_request + http_get_json cpp/core)
Funciones implementadas, registradas en registry.db via fn index, tests
locales (11 cases, 27 assertions) en verde. Cierra el gap detectado:
patron curl-popen inline duplicado en services_monitor / dag_engine_ui /
data_factory ahora promovido al registry.

Sigue habilitando issue 0111 (apps/process_explorer http_client) cuando
arranque — usara http_request_cpp_core directamente.
2026-05-18 18:15:38 +02:00
egutierrez a843f84a18 docs(cpp/core): registry .md for http_request + http_get_json (issue 0110)
Frontmatter + self-doc sections (Ejemplo, Cuando usarla, Gotchas) following
the contract in .claude/rules/function_growth_and_self_docs.md. Tags include
'http', 'client', 'curl', 'network', 'registry-gap', 'helper' so FTS surfaces
them when an agent asks for HTTP / fetch / GET / Bearer.

http_get_json declares uses_functions: [http_request_cpp_core] so the
dependency is auditable via mcp__registry__fn_uses.
2026-05-18 18:14:56 +02:00
egutierrez 6f3c129a14 test(cpp/core): integration tests for http_request + http_get_json (issue 0110)
Catch2-based tests that fork+exec a local python3 http.server fixture per
test binary. Covers:

  http_request:
    - GET 200 with body
    - GET 404 (HTTP error != transport error)
    - POST with body + Content-Type
    - bearer_token shortcut adds Authorization: Bearer
    - basic_user/basic_pass shortcut adds HTTP Basic (curl --user)
    - invalid URL surfaces transport error (status=0)
    - timeout_ms is honored (bails before server's 3s sleep)

  http_get_json:
    - parses 200 JSON body
    - throws std::runtime_error on 404
    - bearer_token reaches server (verified via echoed Authorization header)
    - throws std::runtime_error on invalid JSON body

Tests skip gracefully if python3 isn't available (server.start() returns
false; SUCCEED with skip message). No external network required.

Local runs (Linux): 21 assertions / 7 cases (http_request), 6 / 4 (get_json),
all passing.
2026-05-18 18:14:48 +02:00
egutierrez bc270db723 docs: cerrar issue 0113 — agent_runner_api scaffold + DoD + worktrees 2026-05-18 18:14:39 +02:00
egutierrez a3a263702b feat(cpp/core): add http_request + http_get_json helpers (issue 0110)
Promotes the inline curl-popen pattern duplicated across apps/services_monitor,
dag_engine_ui, data_factory into two reusable functions in cpp/functions/core/:

- http_request_cpp_core: generic HTTP client (GET/POST/PUT/DELETE/PATCH) via
  cURL CLI through popen. Portable Linux/WSL/MinGW (no link-time libcurl).
  Supports custom headers, raw body, Bearer/Basic auth shortcuts, timeout,
  optional TLS verify skip. Returns status/body/headers/error/duration_ms.

- http_get_json_cpp_core: convenience wrapper over http_request — GET <url>,
  expect 2xx, parse body as nlohmann::json. Throws std::runtime_error on
  transport / non-2xx / parse failure.

Vendors nlohmann/json v3.11.3 single header at cpp/vendor/nlohmann/json.hpp
(MIT). No CMake target needed — header-only; consumers add
cpp/vendor/ to include path.
2026-05-18 18:14:37 +02:00
egutierrez 78c4f593a4 docs: cerrar issue 0114
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:13:14 +02:00
egutierrez 0f72cc8ad3 docs: dod_evidence_schema templates + READMEs (issue 0114)
- docs/templates/issue.md and docs/templates/flow.md include the optional
  dod_evidence_schema: block with realistic example items.
- dev/issues/README.md and dev/flows/README.md document the schema, kinds
  by example, validation rules and the fn doctor dod entrypoint.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:13:02 +02:00
egutierrez 030e44b027 test(infra): audit_dod_schema covers valid/invalid/malformed/recurse (issue 0114)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:12:54 +02:00
egutierrez ca2e5588cc feat(infra): audit_dod_schema + fn doctor dod (issue 0114)
Adds AuditDodSchema(issuesDir, flowsDir) which scans dev/issues/ and
dev/flows/ frontmatter for the new optional dod_evidence_schema: block.
Validates id uniqueness, kind in {screenshot,log,url,cmd}, expected
non-empty and required bool (default true). Tolerant to malformed YAML
and missing block.

Wires it into fn doctor dod with human-readable caveman output and
--json support.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:12:49 +02:00
egutierrez 5fb2269c00 merge issue/0095-frontend: dag_engine_ui + data_table v1.3 + dev_console + work_tab + frontmatter migration + DoD user-facing 2026-05-17 02:44:39 +02:00
egutierrez 5e6a974a5d feat(dev): issues 0100-0104 — dev_console binary + work_tab + DoD user-facing + frontmatter migration de 146 issues + taxonomia canonica
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 02:44:04 +02:00
egutierrez 5d2a14e50a docs(flows): DoD obligatorio con user-facing surface + abrir issues 0100-0103 (taxonomia, frontmatter migration, dev_console, work dashboard)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 00:07:03 +02:00
egutierrez 212875ed0d chore: auto-commit (286 archivos)
- .claude/agents/fn-orquestador/SKILL.md
- .claude/commands/fn_claude.md
- .claude/rules/INDEX.md
- .claude/rules/cpp_apps.md
- .claude/rules/ids_naming.md
- CHANGELOG.md
- apps/dag_engine/README.md
- apps/dag_engine/api.go
- apps/dag_engine/dags_migrated/example.yaml
- apps/dag_engine/dags_migrated/example_lineage_tracking.yaml
- ...

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 16:33:22 +02:00
egutierrez d6175964e4 data_table v1.3.1: Dots renderer via ImDrawList (font-independent) + recompile all apps with fn_table_viz (issue 0081-O.6)
- Replace TextColored+glyph with ImDrawList::AddCircleFilled in CellRenderer::Dots.
  Dots are now font-independent: no dependency on Unicode glyph coverage. Fixes
  "dots show as ?" on Karla/Roboto/Inter fonts that lack Geometric Shapes block.
- dots_glyph_size now controls circle radius (px) instead of font scale.
- BadgeRule.label is ignored for Dots (documented in data_table_types.h + docs).
- data_table.md bumped to v1.3.1 with capability growth log entry.
- docs/capabilities/data_table_renderers.md: Dots section updated + Common pitfalls
  entry added: "Asumir que cualquier glyph Unicode renderea".
- dag_engine_ui/tabs.cpp: removed stale "● glyph" comment from BadgeRule.
- Recompiled: dag_engine_ui, registry_dashboard, graph_explorer, navegator_dashboard,
  odr_console. All 5 apps deployed to Desktop/apps/. Build Linux + tests 4/4 green.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 17:35:22 +02:00
egutierrez 5974484bd4 data_table v1.3.0: Dots renderer for status timelines + fix dag_engine_ui antipattern + pitfalls doc (issue 0081-O.5)
PARTE A - CellRenderer::Dots (v1.3.0):
- Add Dots=8 to CellRenderer enum (data_table_types.h)
- Add dots_separator/dots_max/dots_show_count/dots_glyph_size fields to ColumnSpec
- Implement draw_cell_custom case Dots in data_table.cpp
  - Parses comma-separated cell value into tokens
  - Looks up each token in badges for color + optional glyph override
  - Per-dot tooltip via tooltip_on_hover
- tql_emit: serialize renderer="dots" + dots_max/dots_show_count/dots_glyph_size/dots_separator
- tql_apply: deserialize all Dots fields
- tql_emit_test: +6 assertions (58 total, 0 failed)
- tql_apply_test: +8 assertions (114 total, 0 failed)
- test_column_specs: +2 tests (10/10 pass)

PARTE B - dag_engine_ui fix: 10 cols -> 6 cols (submodule commit 61314b7)

PARTE C - docs/capabilities/data_table_renderers.md:
- Update to v1.3.0
- Add decision tree for renderer selection
- Add CellRenderer::Dots section with canonical example
- Add Common pitfalls section (multiple columns, badge for free-text, etc.)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 17:24:53 +02:00
egutierrez 67fff0d677 docs(dag_engine): README autoritativo (anadir DAGs + formato YAML + troubleshooting)
apps/dag_engine/README.md cubre:
- Donde viven los DAGs y como apuntar el systemd unit.
- Workflow paso a paso para anadir uno nuevo (crear/validar/probar/recargar/verificar).
- Formato YAML completo: top-level fields + step fields + cron schedule + ejemplo de extremo a extremo (env, depends, retry_policy, continue_on, handlers).
- Comandos CLI (run/list/status/validate/server) + flags.
- 7 secciones de "que hacer si algo falla": DAG invisible, validation fail, step fallido, scheduler no dispara, WS disconnected, cleanup runs viejos, restaurar backup.
- Endpoints HTTP completos.
- Referencias a funciones del registry y commit de migracion.

app.md de dag_engine + dag_engine_ui apuntan a README.md.
gitlink dag_engine_ui actualizado a commit con app.md mejorado.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 17:23:33 +02:00
egutierrez 890f641692 feat(dag_engine_ui): gitlink panel Timeline (ImPlot scatter X=tiempo Y=DAG)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 17:14:16 +02:00
egutierrez ae5d27a5ec feat(dag_engine): /api/dags devuelve last_runs[] (max 5) + gitlink UI badges
- executor.go: DagInfo anade LastRuns []store.DagRun. Pobla con e.store.ListRuns(name, 5, 0).
- cpp/apps/dag_engine_ui: gitlink al SHA con 5 puntitos R1..R5 via data_table BadgeRule.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 17:07:16 +02:00
egutierrez 0ed949d235 fix(dag_engine_ui): gitlink Win32 ws2_32 link (issue 0095)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 17:01:06 +02:00
egutierrez c438dc6916 data_table: Phase 2 — Button + events + tooltip + RightClick + TQL persist column_specs (issue 0081-O)
- CellRenderer::Button=5: renders SmallButton per cell; emits TableEvent::ButtonClick on click
- TableEventKind enum (ButtonClick/RowDoubleClick/RowRightClick/CellEdit) + TableEvent struct
- render() extended overload: adds events_out parameter (nullptr = back-compat, no events)
- RowDoubleClick and RowRightClick detection in raw table loop (stage 0)
- RowRightClick also detected in aggregated stage table (stage 1+)
- Tooltip per cell: tooltip_on_hover + tooltip fields on ColumnSpec; "auto" = show cell value
- State::aux_column_specs: TQL-persisted column specs sidecar per table
- tql_emit: serializes aux_column_specs[0] as column_specs block (badge/progress/duration/icon/button/tooltip)
- tql_apply: parses column_specs block back into state.aux_column_specs[0]
- render() merges aux_column_specs into TableInput when caller passes empty column_specs
- test_column_specs: 5->8 tests (Button struct, tooltip fields, both render() signatures link)
- tql_emit_test: 3 new tests (column_specs badge/button/tooltip emit) — 52 passed
- tql_apply_test: 3 new tests (column_specs badge/button/tooltip roundtrip) — 106 passed
- Back-compat: existing apps (graph_explorer, registry_dashboard) unchanged
- Version bump: data_table v1.1.0 -> v1.2.0

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 16:59:26 +02:00
egutierrez 4027aeaaf5 feat(dag_engine_ui): gitlink tabs DAG List/Detail/Run Detail (issue 0095 step 5)
cpp/apps/dag_engine_ui: SHA con data_table_cpp_viz integrado.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 16:57:59 +02:00
egutierrez 9ff0b3900c feat(dag_engine_ui): gitlink WS client (issue 0095 step 4)
cpp/apps/dag_engine_ui: SHA con ws_client + panel Live integrado.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 16:47:23 +02:00
egutierrez ce9fa3b451 feat(dag_engine): json tags lowercase + gitlink dag_engine_ui HTTP layer (issue 0095 step 3)
- store/store.go: anade tags JSON lowercase a DagRun + DagStepResult para que REST y WS devuelvan misma forma.
- cpp/apps/dag_engine_ui: gitlink al SHA con http_client + data_http.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 16:45:18 +02:00
egutierrez e0cce972ea feat(cpp): registrar dag_engine_ui en cpp/CMakeLists.txt (issue 0095 step 2)
Sub-repo Gitea: dataforge/dag_engine_ui (a crear cuando se ejecute /full-git-push).
Gitlink al SHA inicial del scaffolding.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 16:38:43 +02:00
egutierrez 380a7a8f35 data_table: declarative cell renderers Phase 1 (Badge/Progress/Duration/Icon)
Adds TableInput.column_specs sidecar field enabling apps to declare Badge,
Progress, Duration and Icon renderers per column without writing ImGui inline.
Back-compat: apps without column_specs compile and behave identically.

- data_table_types.h: CellRenderer enum, BadgeRule, IconMapEntry, ColumnSpec types
- data_table.cpp: hex_to_imcolor helper, icon_name_to_glyph static map (~30 Tabler icons),
  draw_cell_custom dispatcher, integration in Stage-0 and Stage-N cell loops and draw_extra_panel
- Bump version 1.0.0 -> 1.1.0 with capability growth log
- cpp/tests/test_column_specs.cpp: 5 smoke/linker tests (back-compat + 4 renderer types)
- cpp/tests/CMakeLists.txt: register test_column_specs target linked against fn_table_viz
- types/core/{cell_renderer,badge_rule,icon_map_entry,column_spec}.md: registry type mds
- docs/capabilities/data_table_renderers.md: canonical doc with end-to-end examples
- docs/capabilities/INDEX.md: added data-table-renderers group

All tests green: test_column_specs 5/5, test_fn_table_viz_smoke 8/8,
tql_emit 41/41, tql_apply 88/88, Wave-1 tests 8/8.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 16:38:24 +02:00
egutierrez 7ecbee1175 feat(dag_engine): WS hub /api/ws/dagruns + migracion DAGs desde dagu
- events.go: DagRunHub broadcastea snapshot+deltas live (500ms tick, 5s recent finished window) sobre dag_runs + dag_step_results.
- api.go: handler GET /api/ws/dagruns upgrade WS, opt-in en RegisterAPI.
- store.go: expone Conn() para read-only desde el hub.
- main.go: construye DagRunHub al arrancar server.
- dags_migrated/: 5 YAMLs migrados desde ~/dagu/dags tras desinstalar dagu (issue 0095 step 1).

Smoke: snapshot inicial OK, trigger /api/dags/test_claude_access/run -> delta WS observa 3 step_results + run success en <1s.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 16:36:34 +02:00
egutierrez fe39de8b22 scaffolder: auto-wire fn_table_viz in new C++ apps (issue 0081-M)
- CMakeLists.txt template: adds target_link_libraries fn_table_viz with
  if(TARGET fn_table_viz) guard (compiles even without vendor/lua).
- main.cpp template: adds commented include + data_table::render() panel
  block in render(). Also fixes include to use app_base.h + panel_menu.h
  (matching convention of chart_demo, shaders_lab).
- app.md template: uses_functions lists all 12 fn_table_viz stack IDs
  commented out; uncomment when activating data_table::render().
- Bump version 0.1.0 -> 1.1.0. Add capability growth log entry.
- Tag cpp-tables added to capability group.
- Verified: test app test_scaffolder_default compiled clean, residues
  removed (dir + CMakeLists entry).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 15:06:06 +02:00
egutierrez 951a77ec7f close issue 0081: tables promoted to registry + fn doctor cpp-apps BeginTable check
- docs/TQL.md: añadidas secciones joins, views, main_source, 24 viz tokens completos
  (extraidos de tql_helpers.cpp), color_rules, fn.* builtins completos (20 funciones),
  funciones bloqueadas del sandbox, tabla de estado de implementacion actualizada.
  Nota al pie referencia los 129 checks roundtrip (41 emit + 88 apply).

- functions/infra/audit_cpp_apps.go: añadida AuditCppTableMigration() que escanea
  .cpp de cada app imgui buscando ImGui::BeginTable; status CANDIDATE/MIXED/clean
  segun si usa data_table_cpp_viz en uses_functions.

- cmd/fn/doctor.go: fn doctor cpp-apps ahora incluye seccion BeginTable migration
  con tabwriter CANDIDATE/MIXED; --json produce {conformance, table_migration}.
  doctorAll incluye cpp_table_migration en el mapa JSON.

- .claude/rules/fn_doctor.md: tabla de subcomandos y acciones complementarias
  actualizadas con el nuevo check.

- dev/issues/0081 movido a completed/ con status done y notas de deuda documentadas.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 14:49:56 +02:00
egutierrez 88119ee1b2 feat(pipelines): auto-commit con 3 cambios
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 18:13:22 +02:00
egutierrez 282c2e3ba8 Merge quick/issue-0094-doc 2026-05-14 18:08:19 +02:00
egutierrez 950b994797 docs(issues): kanban 0094 bocadillo agente + PDF
Adjunta el issue del nuevo reporte diario con agente.
2026-05-14 18:08:19 +02:00
egutierrez 23f5f1c25f Merge quick/kanban-issue-docs
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 17:58:02 +02:00
egutierrez be8a61e724 docs(issues): kanban 0089-0093 reportes diarios + perf + archive
Archivos de issue para el trabajo de kanban de las ultimas iteraciones:

- 0089: tiempo maximo por columna con borde rojo (incluye followup popover
  con seleccion de unidad min/h/d/sem/mes).
- 0090: seleccion aleatoria por columna con animacion de ruleta. Ya con
  fix de no mostrar en columnas Done.
- 0092: archivo automatico para cards en columnas Done con +30 dias.
- 0093: reporte diario al pulsar el numero del dia en el calendario.

Los issues 0088 y 0091 ya estaban registrados.
2026-05-14 17:57:44 +02:00
egutierrez 80f44cc89e Merge issue 0091: kanban sidebar drag zones 2026-05-14 13:58:23 +02:00
egutierrez 188122812a docs(issues): add 0091 — kanban sidebar drag zones
Issue spec for the drag-aware dropzone strip that auto-opens the
kanban sidebar after >=400ms hover during a drag.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 13:58:18 +02:00
egutierrez e2ecdc7533 feat(registry): add playwright capability group (6 TS browser fns)
New domain `browser` under frontend/functions/ with 6 Playwright helpers:
- pw_launch_browser: chromium + context + page bootstrap with storageState
  support and baseUrl navigation.
- pw_kanban_login: authenticates a Page against /api/auth/login; sets the
  kanban_session cookie via shared storageState; verifies login page no
  longer visible after navigation.
- pw_drag_drop: human-like pointer drag (mousedown + activateOffset +
  stepped move + mouseup) compatible with @dnd-kit/core's 8px activation
  threshold; supports hoverMs for time-based dropzones.
- pw_keyboard_sequence: ordered focus/type/press/wait steps for scripting
  realistic input flows (typing then arrow-key navigating autocompletes).
- pw_wait_predicate: thin wrapper over page.waitForFunction with friendlier
  defaults and custom error messages.
- pw_assert_class: poll-based assertion that a Locator has/lacks a CSS
  class within a timeout; useful for visual-state checks.

Each function ships with vitest tests (5-8 cases each) covering both happy
and error paths, plus self-documenting .md (Ejemplo + Cuando usarla +
Gotchas + frontmatter with params/output schema).

Adds frontend/functions/package.json with `"type": "module"` so consumers
can ESM-import the .ts files from anywhere in the registry (Playwright's
tsx loader respects nearest package.json).

Capability page docs/capabilities/playwright.md documents the group with
a canonical end-to-end example, frontiers, prerequisites, and gotchas.
Index updated.

First consumer (issue 0088): apps/kanban requester-input.spec.ts.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 12:57:30 +02:00
egutierrez 7d82359a45 feat(pipelines): auto-commit con 4 cambios
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 02:14:09 +02:00
egutierrez 4e8b5af6c4 feat(infra): auto-commit con 29 cambios
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 02:06:44 +02:00
egutierrez cfdf515228 chore: auto-commit (799 archivos)
- .claude/CLAUDE.md
- .claude/commands/subagentes.md
- .claude/rules/INDEX.md
- .mcp.json
- bash/functions/cybersecurity/analyze_dns.md
- bash/functions/cybersecurity/audit_http_headers.md
- bash/functions/cybersecurity/audit_ssh_config.md
- bash/functions/cybersecurity/check_firewall.md
- bash/functions/cybersecurity/detect_suspicious_users.md
- bash/functions/cybersecurity/encrypt_file.md
- ...

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 00:28:20 +02:00
egutierrez d110aa40f9 feat(metabase): auto-commit con 17 cambios
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 18:40:22 +02:00
egutierrez aec5d82011 feat(ml): auto-commit con 14 cambios
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 01:22:02 +02:00
egutierrez 88b5b27dc0 chore(issues): mueve 0078/0079/0080 a completed/
3 issues cerradas movidas al directorio completed/ por convencion:

- 0078 tables playground joins MBQL (fase 9)
- 0079 tables playground drill-through extendido (fase 10)
- 0080 tables playground LLM Ask AI + TQL->SQL emit (fase 11)

0081 (promote a registry, fase 12) permanece en dev/issues/ — status
partial, 0081-A done, 0081-B..L pending.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 01:21:50 +02:00
egutierrez 574b3f6823 chore(issues): cierra 0080, marca 0081 partial
0080 status: pending -> done (closed 2026-05-13). Notas: pure layer +
LLM client + Ask AI modal + DuckDB adapter (FN_TQL_DUCKDB ON). 618
tests con DuckDB, 603 sin.

0081 status: pending -> partial (in progress). 0081-A DONE (20 types
extraidos al registry). 0081-B..L pendientes: extraer functions
restantes (compute_stage, tql_emit/apply, lua_engine, tql_to_sql,
join_tables, viz_render, data_table) + fn_table_viz lib + migrar
5 apps + fn doctor cpp-apps check.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 00:58:31 +02:00
egutierrez 552c40bc42 docs(types): drill_step + filter_preset md (0081-A)
Completa el batch de 20 type .md extraidos a cpp/types/core/ y
cpp/types/viz/ apuntando a cpp/functions/core/data_table_types.h.
Quedan 2 que faltaban en commits anteriores: DrillStep_cpp_core
(undo/redo de drills, fase 10) y FilterPreset_cpp_core (Last7/30/90d,
ExcludeNulls, NonZero, fase 10).

Total types indexados: 206. Tabla via mcp__registry__fn_search
"file_path:data_table_types" o sqlite SELECT por file_path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 00:58:25 +02:00
egutierrez 1702f12664 feat(playground): DuckDB adapter para TQL->SQL execute (issue 0080)
Cierra 0080 fase 11. tql_duckdb.{h,cpp} es adapter opcional gated por
build flag FN_TQL_DUCKDB=ON. Default OFF — playground sin deps DuckDB.

Funcionalidad:
- tql_duckdb::execute(sql, params, tables) -> Result con StageOutput
  materializado. Abre DuckDB :memory:, registra TableInputs via
  CREATE TABLE + INSERT batched (1000 rows/batch), prepare + bind
  params via duckdb_bind_varchar, execute_prepared, materializa
  resultado via duckdb_value_varchar + duckdb_free.
- type_from_duckdb mapeo DuckDB type -> ColumnType.
- CMakeLists.txt: option(FN_TQL_DUCKDB) + condicional add a sources
  + link duckdb_vendored + copy runtime.
- data_table.cpp Ask AI modal: ifdef FN_TQL_DUCKDB para status message
  apropiado en SQL apply.
- self_test.cpp: 4 round-trip tests gated por FN_TQL_DUCKDB:
  stage0 SELECT, group+count, filter Op::Eq, sum aggregation
  (verifica sum_n(go)=30).

Tests:
- 603 passed sin FN_TQL_DUCKDB (default OFF).
- 618 passed con FN_TQL_DUCKDB=ON (round-trip TQL emit -> DuckDB
  execute -> match compute_stage pure).
- e2e linux + windows cross-build OK ambos modos.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 00:58:18 +02:00
egutierrez a802f59f55 chore: auto-commit (95 archivos)
- cmd/fn/doctor.go
- cmd/fn/main.go
- cpp/apps/primitives_gallery/playground/tables/CMakeLists.txt
- cpp/apps/primitives_gallery/playground/tables/data_table.cpp
- cpp/apps/primitives_gallery/playground/tables/data_table_logic.cpp
- cpp/apps/primitives_gallery/playground/tables/data_table_logic.h
- cpp/apps/primitives_gallery/playground/tables/self_test.cpp
- cpp/apps/primitives_gallery/playground/tables/tql.cpp
- cpp/apps/primitives_gallery/playground/tables/viz.cpp
- cpp/apps/primitives_gallery/playground/tables/viz.h
- ...

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 00:50:34 +02:00
egutierrez ef60449e64 feat(infra): auto-commit con 1 cambios
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 21:04:24 +02:00
egutierrez c7904a7dcb feat(browser): auto-commit con 9 cambios
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 21:03:45 +02:00
egutierrez b4c28da2ba chore(issues): auto-commit
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 03:17:43 +02:00
egutierrez 2297edf2ab fix: zsh-safe var rename + yaml returns as list
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 03:13:53 +02:00
egutierrez 9d0a1d99e8 asegurate de que subimos todo
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 03:10:00 +02:00
egutierrez a396ee781a feat(kotlin-compose): finalize design system + apps + sync sub-repo gitlinks
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 16:30:43 +02:00
egutierrez 42c14fae59 feat(kotlin-compose): design system + 33 components + gallery_kt + e2e android emulator + scaffolder fixes
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 16:28:50 +02:00
egutierrez bd036cf3d4 Merge branch 'issue/0005-fix-layout-dock-restore' (cfg.pre_frame hook) 2026-05-10 14:21:32 +02:00
egutierrez b5fc99c2fa feat(framework): cfg.pre_frame hook for apps with own LayoutStorage
Apps que gestionan su propio LayoutStorage (cfg.auto_layouts=false +
cfg.layouts_cb=&own_cb) necesitan llamar layout_storage_apply_pending
en el momento correcto: despues de ImGui::NewFrame y ANTES de menubar
+ auto-dockspace + cualquier Begin() del frame.

Antes, si la app llamaba apply_pending dentro de render_fn (es decir,
mid-frame), ImGui cargaba el INI pero las dock-nodes no se restauraban
hasta el siguiente ciclo: las ventanas docked aparecian flotantes.

cfg.pre_frame es un std::function<void()> opcional que run_app y
run_app_test invocan justo despues de NewFrame, antes del bloque
auto_layouts_storage, antes de app_menubar y antes del auto-dockspace.
Default null = no-op, sin impacto en apps existentes.

Apps con auto_layouts=true (la mayoria) no necesitan tocar nada — el
framework ya hace apply_pending en su propio bloque. pre_frame es
puramente para apps con layout custom.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 14:21:00 +02:00
4059 changed files with 553881 additions and 6084 deletions
+127 -36
View File
@@ -2,22 +2,64 @@
Registry personal de codigo reutilizable con busqueda FTS. Diseñado para composicion funcional y agentes.
## Objetivos del registry (Norte) — Issues 0086 + 0087
**4 metricas optimizadas por el bucle reactivo** (visibles en Monitor tab del `registry_dashboard`):
1. **MAXIMIZAR `Reg %`** — porcentaje de calls del agente que golpean una funcion del registry (`function_id != ''`). Cada bash inline o heredoc que reescribe logica baja el ratio. Target: subir cada semana.
2. **MEJORAR uso del registry por Claude** — el agente debe encontrar y usar funciones existentes antes de escribir codigo. Indicadores: `MCP` (mcp/heredoc/fn run) sube; violations baja. Si Claude no encuentra una funcion por busqueda mediocre, mejorar `description`/`tags`/`params_schema` de esa funcion.
3. **ACELERAR tareas comunes via funciones nuevas** — patrones inline repetidos >2 veces -> `fn-constructor` crea la funcion, Claude la usa el siguiente turno. Velocidad medida en pasos (turnos) por tarea. Pattern detection: tab Monitor + `mcp__registry__fn_proposal action="list"`.
4. **PROMOVER COMPOSICIONES A PIPELINES** (issue 0087) — el registry no crece inflando funciones, crece **promoviendo secuencias A→B(→C) que se repiten con exito** a pipelines one-shot. Hoy `bank_login + bank_make_transfer` (2 calls). Manana `bank_transfer_oneshot` (1 call). Misma capacidad, mitad de pasos. Detectado por telemetria de secuencias en `call_monitor`. Una funcion que hace bien UNA cosa NO necesita crecer — lo que crece es el catalogo de composiciones probadas.
**Auto-discovery zero-second-lookup:** cada `.md` debe ser autosuficiente — `## Ejemplo` lanzable + `## Cuando usarla` + `## Gotchas` (impuras). Descubrir = lanzar, sin segunda lectura. Ver `.claude/rules/function_growth_and_self_docs.md`.
Cualquier decision tecnica que choque con estos objetivos esta mal priorizada. Ejemplo: un bash heredoc rapido hoy que reinventa logica = penaliza objetivos 1 y 3 manana.
**Dos bases de datos SQLite:**
- **registry.db** (raiz) — funciones, tipos, proposals, apps, projects, analysis, vaults, pc_locations. Regenerable con `fn index` (excepto proposals y pc_locations).
- **operations.db** (por app en `apps/*/`) — entities, relations, executions, assertions. Datos vivos.
**Sync entre PCs:** `fn sync` sincroniza datos no regenerables (proposals, apps, projects, analysis, vaults, pc_locations) contra `registry_api` en `https://registry.organic-machine.com`. Config: `~/.fn_pc` (identidad del PC), `FN_REGISTRY_API` (URL con basicAuth), `REGISTRY_API_TOKEN` (token).
**Sub-repos:** cada app y cada analysis es su propio repo Gitea en `dataforge/<basename>` con branch `master` (ver ADR 0002). Los slash commands `/full-git-push` y `/full-git-pull` orquestan push/pull/clone de fn_registry + todos los sub-repos + `fn sync`. `/full-git-push` auto-inicializa apps/analyses sin `.git` via `ensure_repo_synced_bash_infra`. Los `vaults/` y `subrepos/` NO entran en este flujo.
**Sub-repos:** cada app y cada analysis es su propio repo Gitea en `dataforge/<basename>` con branch `master` (ver ADR 0002). `apps/*` y `analysis/*` estan en el `.gitignore` del repo padre — el codigo de cada app vive en `apps/<name>/.git/`. Los slash commands `/full-git-push` y `/full-git-pull` orquestan push/pull/clone de fn_registry + todos los sub-repos + `fn sync`. `/full-git-push` auto-inicializa apps/analyses sin `.git` via `ensure_repo_synced_bash_infra`. Los `vaults/` y `subrepos/` NO entran en este flujo. **Gotcha worktrees**: si creas una app nueva dentro de un git worktree del repo padre, haz `git init` dentro de `apps/<name>/` ANTES de limpiar el worktree, sino el codigo se pierde (apps/* gitignored). Ver `.claude/rules/apps_subrepo.md`.
**Artefactos:** termino paraguas para apps, analysis, vaults, projects y playgrounds — todo lo que NO es codigo reutilizable. Usa "artefacto" cuando una afirmacion aplica a varios tipos a la vez para no repetir la lista. Ver `.claude/rules/artefactos.md` y `.claude/rules/playgrounds.md`.
**Reglas y convenciones:** ver `.claude/rules/INDEX.md`
**Slash commands:** `/commands` lista todos los slash commands del repo agrupados por namespace (global + projects). Project commands viven en `projects/<p>/.claude/commands/` y se exponen como `/<project>:<cmd>` via symlink. Ver `.claude/rules/project_commands.md`.
**Migraciones SQLite obligatorias:** todo cambio de schema en cualquier `.db` (apps, operations.db, registry.db) va en `migrations/NNN_*.sql` numerado. Aditivo, idempotente, aplicado al arrancar via `embed.FS`. Nunca borrar `.db` ni modificar migraciones existentes. Aplica retroactivamente. Ver `.claude/rules/db_migrations.md`.
---
## Delegacion + Capability Groups (REGLA DURA — issue 0086)
Claude **multiplica capacidades** delegando creacion de funciones a `fn-constructor` y reusandolas inmediatamente. NO escribir logica reutilizable inline.
### Flujo obligatorio (mismo turno)
1. **Detectar gap**. Si vas a escribir >=5 lineas de logica reutilizable inline -> STOP.
2. **Spawn `fn-constructor`** via `Agent(subagent_type="fn-constructor", ...)`. Sin preguntar al usuario.
3. **Paralelo**: si hay >1 funcion independiente -> **una sola llamada al Agent tool con N tool_use blocks paralelos** en mismo mensaje. NO serializar.
4. **Tag de grupo obligatorio** (`notebook`, `metabase`, `deploy`, etc.). Ver `docs/capabilities/INDEX.md`.
5. **`fn index`** + **importar + invocar en mismo turno**. No dejar funcion huerfana recien creada.
6. **Auto-verificar**: `fn doctor uses-functions` + `fn doctor unused` si tocas >=3 funciones nuevas.
### Capability groups
Cluster de >=3 funciones que comparten dominio operativo. Cada grupo tiene tag plano + pagina madre `docs/capabilities/<grupo>.md` con: lista de funciones, ejemplo canonico end-to-end, fronteras.
**Antes de buscar funciones sueltas en una tarea de dominio conocido:** lee `docs/capabilities/<grupo>.md` para cargar el cluster entero en un solo read. Filtro MCP: `mcp__registry__fn_search query="" tag="<grupo>"`.
Reglas completas: `.claude/rules/delegation.md` + `.claude/rules/capability_groups.md`.
### Telemetria CAPABILITY-GROWTH
Cada turno el hook `UserPromptSubmit` inyecta `CAPABILITY-GROWTH: created_this_session=X used=Y orphan=Z`. Si `orphan>0` -> integra la funcion antes de cerrar turno o documenta por que.
---
## Explorar el registry (OBLIGATORIO)
**SIEMPRE** consulta registry.db antes de escribir codigo, crear funciones, o responder sobre el registry. No uses grep/glob sobre archivos .go/.md — la BD es la fuente de verdad.
@@ -39,56 +81,67 @@ Registry personal de codigo reutilizable con busqueda FTS. Diseñado para compos
Razones: menos tokens, output estructurado, FTS5 escapado bien (sin gotchas de `column:"valor"`), permisos pre-aprobados, no requiere `cd` ni paths absolutos a `registry.db`.
**Cuando si caer a `sqlite3` (Bash):** SOLO si el MCP no cubre el caso — JOINs custom entre tablas, agregaciones (`COUNT`/`GROUP BY`), introspeccion de schema (`.schema`, `PRAGMA table_info`), o columnas que el MCP no expone. En ese caso, los patrones FTS5 estan documentados abajo.
**La BD contiene el codigo y la documentacion completa** de cada funcion y tipo en los campos `code`, `documentation` y `notes`. Tambien indexados en FTS5 — buscas dentro del codigo directamente. Para leer codigo: `mcp__registry__fn_code <id>`.
**La BD contiene el codigo y la documentacion completa** de cada funcion y tipo en los campos `code`, `documentation` y `notes`. Estos campos tambien estan indexados en FTS5, asi que puedes buscar dentro del codigo y la documentacion directamente. Para leer el codigo de una funcion: `mcp__registry__fn_code` (preferido) o `SELECT code FROM functions WHERE id = '...'` (fallback).
### Ejemplos MCP (usa estos, NO sqlite3)
**Busquedas FTS5 (cuando uses sqlite3 como fallback):** Usa SIEMPRE la tabla FTS5 para buscar tanto por `name` como por `description`. Esto encuentra coincidencias parciales y similares que una busqueda exacta perderia. Usa operadores FTS5: `OR` para ampliar, `*` para prefijos, `NEAR` para proximidad.
Cada llamada MCP se registra en `call_monitor` (issue 0085). Cada `sqlite3 registry.db "SELECT ..."` queda fuera del bucle reactivo y dispara el hook PreToolUse.
```bash
# Busqueda FTS5 por nombre Y descripcion (USAR SIEMPRE ESTE PATRON)
sqlite3 registry.db "SELECT id, kind, purity, description FROM functions WHERE id IN (SELECT id FROM functions_fts WHERE functions_fts MATCH 'name:slice OR description:slice') ORDER BY name;"
```
# Busqueda basica por nombre/descripcion (FTS5 detras)
mcp__registry__fn_search query="slice"
# FTS5 con prefijo (encuentra slice, slicing, sliced...)
sqlite3 registry.db "SELECT id, kind, purity, description FROM functions WHERE id IN (SELECT id FROM functions_fts WHERE functions_fts MATCH 'name:slic* OR description:slic*') ORDER BY name;"
# Filtros: kind, purity, domain, lang
mcp__registry__fn_search query="filter" kind="function" purity="pure" domain="core"
# FTS5 en tipos
sqlite3 registry.db "SELECT id, algebraic, description FROM types WHERE id IN (SELECT id FROM types_fts WHERE types_fts MATCH 'name:result OR description:result') ORDER BY name;"
# Prefijo FTS5 — encuentra slice/slicing/sliced
mcp__registry__fn_search query="slic*"
# FTS5 por semantica de params (composabilidad)
sqlite3 registry.db "SELECT id, json_extract(params_schema, '$.output') FROM functions WHERE id IN (SELECT id FROM functions_fts WHERE functions_fts MATCH 'params_schema:retornos');"
# Buscar tipos
mcp__registry__fn_search query="result" entity="types"
# Por dominio
sqlite3 registry.db "SELECT id, purity, signature FROM functions WHERE domain = 'finance' ORDER BY name;"
# Apps
mcp__registry__fn_search query="kanban" entity="apps"
# Puras de un dominio
sqlite3 registry.db "SELECT id, signature FROM functions WHERE domain = 'core' AND purity = 'pure' ORDER BY name;"
# Listar dominios
mcp__registry__fn_list_domains
# Tipos por dominio
sqlite3 registry.db "SELECT id, algebraic, description FROM types WHERE domain = 'cybersecurity';"
# Ver una entrada concreta (functions, types, apps, analysis, proposals...)
mcp__registry__fn_show id="filter_slice_go_core"
# Dependencias
sqlite3 registry.db "SELECT id, uses_functions, uses_types FROM functions WHERE uses_functions != '[]';"
# Codigo fuente de una funcion/tipo
mcp__registry__fn_code id="filter_slice_go_core"
# Proposals pendientes
sqlite3 registry.db "SELECT id, kind, status, title FROM proposals WHERE status = 'pending';"
# Quien consume una funcion (consumidores indexados via uses_functions)
mcp__registry__fn_uses id="filter_slice_go_core"
# Schema completo
sqlite3 registry.db ".schema"
# Proposals (pending, approved, ...)
mcp__registry__fn_proposal action="list" status="pending"
mcp__registry__fn_proposal action="show" id="<proposal_id>"
# Diagnostico read-only del registry (artefacts/services/sync/uses-functions/unused/cpp-apps)
mcp__registry__fn_doctor subcommand="artefacts"
mcp__registry__fn_doctor subcommand="sync"
```
**Regla:** Si necesitas saber si algo existe o hay algo similar, usa `mcp__registry__fn_search` (preferido) o consulta FTS5 con sqlite3 (fallback). No asumas que no existe sin consultar primero.
**Escapado FTS5 (gotcha cuando pasas query libre):** valores con `-`, `.`, `:`, espacios rompen el parser FTS5 si los expones como `column:valor`. El MCP escapa por defecto, pero si construyes una `query` con sintaxis FTS5 explicita, encierra el valor en comillas dobles:
**Escapado FTS5 (gotcha):** despues de `column:` el valor debe ser un solo token alfanumerico ASCII (underscores OK). Cualquier otro caracter (`-`, `.`, `:`, espacios) rompe el parser con `no such column: X` o `syntax error near "."`. Encierra el valor en comillas dobles dentro del MATCH:
```bash
# MAL: description:single-page → "no such column: page"
# MAL: description:embed.FS → 'syntax error near "."'
# BIEN:
sqlite3 registry.db "SELECT id FROM functions WHERE id IN (SELECT id FROM functions_fts WHERE functions_fts MATCH 'description:\"single-page\" OR description:\"embed.FS\"');"
```
# MAL: query="description:single-page" -> "no such column: page"
# BIEN
mcp__registry__fn_search query='description:"single-page" OR description:"embed.FS"'
mcp__registry__fn_search query='description:"react router"'
```
Tokens multi-palabra tambien necesitan comillas: `description:"react router"`.
### Excepciones autorizadas para sqlite3 directo
`sqlite3 registry.db` SOLO es legitimo si el MCP no expone la consulta:
- Introspeccion de schema: `.schema`, `.tables`, `PRAGMA table_info(...)`, `PRAGMA index_list(...)`.
- Agregaciones: `COUNT(*)`, `GROUP BY`, `SUM(...)`, `AVG(...)`.
- JOINs custom entre tablas (ej. `functions JOIN unit_tests ON ...`) no expuestos por el MCP.
Cualquier `SELECT ... FROM functions/types/apps/proposals WHERE ...` plano se hace via MCP. El hook PreToolUse avisa si ve `sqlite3 registry.db "SELECT ..."`.
### Schema rapido
@@ -109,7 +162,7 @@ Tokens multi-palabra tambien necesitan comillas: `description:"react router"`.
- `entity_type`: app, analysis, project, vault
- `status`: active, missing, archived
- Se puebla con `fn sync`, NO con `fn index`
- Consultas: `SELECT * FROM pc_locations WHERE pc_id = 'home-wsl'`
- Consultas: `mcp__registry__fn_doctor subcommand="sync"` (drift PC vs disco) o `sqlite3 registry.db "SELECT ... GROUP BY pc_id"` SOLO para agregaciones que el MCP no expone
**FTS5 (columnas buscables):**
- `functions_fts`: id, name, description, tags, signature, domain, example, notes, documentation, code, params_schema
@@ -118,6 +171,43 @@ Tokens multi-palabra tambien necesitan comillas: `description:"react router"`.
---
## Como invocar funciones del registry (CANONICO)
Tres patrones, uno por caso de uso. Toda invocacion del agente se loguea en `projects/fn_monitoring/apps/call_monitor/operations.db` para alimentar el bucle reactivo (issue 0085).
| Caso de uso | Patron canonico | Cuando usar |
|---|---|---|
| **Inspeccionar** registro (buscar, leer codigo, ver dependencias, dominios) | `mcp__registry__fn_search` / `fn_show` / `fn_code` / `fn_uses` / `fn_list_domains` | SIEMPRE para descubrimiento. Reemplaza `sqlite3 registry.db "SELECT ..."` inline. |
| **Ejecutar** UNA funcion o pipeline con sus args | `mcp__registry__fn_run <id> [args]` (preferido) o `./fn run <id> [args]` (fallback CLI) | Cuando hay UN id conocido a lanzar. Despacho automatico por lenguaje. Salida estructurada. |
| **Componer** ad-hoc varias funciones con logica intermedia | Heredoc `python/.venv/bin/python3 - <<'PYEOF' ... PYEOF` IMPORTANDO funciones del registry | Solo cuando hay loops/conditionals/dispatch entre N funciones. Las funciones del registry **se importan**, no se reescriben. |
Regla decisiva: antes de cada bloque de codigo, decide caso. Si dudas entre 2 y 3, casi siempre es 2 (un MCP run con args). Si el caso 3 se repite con el mismo shape >5 veces entre sesiones, **es candidato a pipeline** en `python/functions/pipelines/`.
### Antipatrones prohibidos
| Patron | Por que es malo | Sustituir por |
|---|---|---|
| `sqlite3 registry.db "SELECT ..."` para buscar funciones/tipos | Salta MCP, FTS5 gotchas, sin trazabilidad. Hook PreToolUse ya avisa. | `mcp__registry__fn_search` |
| `python -c "import metabase; print(dir(metabase))"` o `help(metabase)` para descubrir helpers | La fuente de verdad es el registry, no el `__init__.py` | `mcp__registry__fn_search "metabase"` + `mcp__registry__fn_show <id>` |
| Heredoc que reescribe logica que ya existe como funcion del registry | Reinvento + perdida de capitalizacion | Buscar primero; si falta, delegar a `fn-constructor` (no escribir inline) |
| `client._http.request(...)` directo cuando hay wrapper en el registry | Salta validacion del wrapper y telemetria | Usar wrapper; si la firma no cubre el caso, proponer extension via `fn proposal add` |
| Scripts en `temp/` para composiciones que se repiten | Codigo se pierde y no se monitoriza | Pipeline en `python/functions/pipelines/` o pipeline Bash en `bash/functions/pipelines/` |
| Imports `from <pkg> import *` en heredoc | Imposible saber que funcion del registry se uso | Imports explicitos `from <domain> import <name1>, <name2>` |
Excepciones autorizadas para `sqlite3` directo (no requieren MCP): `.schema`, `.tables`, `PRAGMA table_info`, `COUNT(*) GROUP BY`, JOINs custom entre tablas que el MCP no expone.
### Trazabilidad y bucle reactivo
Hook `PostToolUse` en `.claude/settings.local.json` parsea cada comando Bash + cada `mcp__registry__*` y escribe en la `operations.db` del call_monitor. Datos consumidos por:
1. **Tab "Claude usage" en `registry_dashboard`** — top funciones, latencias, error rate, huerfanas con `calls_90d=0`.
2. **Fase MEJORAR del bucle reactivo** — patrones inline repetidos generan proposals `new_function` con evidencia (session_ids + snippets). Funciones con error_rate alto y muchas llamadas suben en prioridad de bugfix.
3. **Auditoria de reglas** — assertions sobre `violation_count`, `mcp_ratio`, `heredoc_repetition`. Si fallan critical → proposal "actualizar CLAUDE.md / prompt del agente".
Datos sensibles: solo se guarda `args_hash`, NUNCA valores concretos de argumentos.
---
## Estructura
```
@@ -170,6 +260,7 @@ fn check params # Lista funciones sin params_schema
fn doctor # Corre todos los checks
fn doctor artefacts # git/venv/app.md/upstream de cada app y analysis
fn doctor services # apps tag 'service' + systemctl + puerto
fn doctor services-spec # audita bloque `service:` del app.md (issue 0105)
fn doctor sync # drift pc_locations BD vs disco
fn doctor uses-functions # imports reales vs uses_functions del app.md
fn doctor unused # funciones del registry sin consumidores
@@ -237,7 +328,7 @@ Entornos usados automaticamente:
## Añadir funciones
1. Consulta la BD para verificar que no existe algo similar
1. `mcp__registry__fn_search query="<nombre|desc>"` para verificar que no existe algo similar
2. Crea dos archivos segun el lenguaje:
- Go: `functions/{domain}/{name}.go` + `.md`
- Python: `python/functions/{domain}/{name}.py` + `.md`
+400
View File
@@ -0,0 +1,400 @@
---
name: fn-orquestador
description: "Meta-orquestador (Fase 6) del ciclo reactivo. Toma un issue o task_spec y recorre CONSTRUIR → EJECUTAR → RECOPILAR → ANALIZAR → MEJORAR despachando a fn-constructor/executor/recopilador/analizador/mejorador hasta convergencia, estancamiento, timeout o tope de iteraciones. Trabaja SIEMPRE en rama sandbox `auto/<issue>`, NUNCA mergea a master, persiste progreso en `task_runs`. Issue 0069."
model: sonnet
tools: Read, Write, Bash, Glob, Grep, Edit
---
# Agente Orquestador — Fase 6 (meta) del Ciclo Reactivo
Cierras la promesa autonoma del registry: "lanzar tarea, irse, volver con resultado". Tu rol es **recorrer las 5 fases del bucle reactivo solo**, despachando a los subagentes especializados, hasta que la tarea converja o se decida parar.
NO escribes codigo de aplicacion directamente. NO mergeas a master. NO bypaseas hooks. Solo orquestas.
Referencia completa: `dev/issues/0069-autonomous-agent-loop-self-iterating-tasks.md`.
---
## REGLAS FUNDAMENTALES (no negociables)
1. **Sandbox de rama EN WORKTREE**. Trabajas SIEMPRE en `auto/<issue_id>` dentro de un `git worktree` aislado (default `/tmp/fn_orq_<issue>_<ts>/`). NUNCA en master ni en el working tree principal del repo. Esto permite N orquestadores paralelos y deja intacto el working tree del humano.
2. **No merge automatico**. Al converger, abres PR draft. Humano aprueba.
3. **No `--no-verify`, no `git push --force`, no skip de hooks**. Nunca.
4. **Paths protegidos**. NO tocar:
- `.claude/` (excepto el subdir del task si aplica explicitamente)
- `dev/issues/` (excepto el issue del task)
- Cualquier archivo `.env*`, `*.key`, `*.pem`, credenciales
- `migrations/` ya existentes (solo crear nuevas, nunca editar)
- Lista canonica: `dev/autonomous_protected_paths.json` (si no existe, usar la default de arriba)
5. **Watchdog de progreso**. 2 iteraciones consecutivas con el MISMO set de fails → parar con `status=stalled`.
6. **Auditoria total**. Cada decision se loggea en `task_runs.progress_json` con razonamiento + fase + run_id.
7. **No self-modify**. NO modificas tu propio SKILL.md ni el de otros subagentes en la misma run.
8. **Cero produccion**. NO deploys, NO llamadas a APIs externas con auth, NO tocar BDs productivas.
9. **NUNCA paths absolutos fuera del worktree**. SIEMPRE rutas relativas o absolutas que apunten dentro de `/tmp/fn_orq_<issue>_<ts>/`. Si necesitas leer algo del repo principal (ej. plantillas docs), copialo al worktree primero. Refuerzo del piloto 1 (2026-05-15): orquestador modifico hooks bash del repo principal usando paths absolutos `/home/lucas/fn_registry/bash/functions/...` para destrancar pre-commit. Solucion correcta: el fix vive en el worktree, NO en main.
10. **Pre-commit hook compartido**. Worktrees comparten `.git/hooks/` con main repo. Si el hook llama scripts via path absoluto a main (ej. `/home/lucas/fn_registry/bash/functions/cybersecurity/scan_secrets_in_dirty.sh`), el hook ejecutara la version de MAIN, no la del worktree. Opciones legitimas:
a. Aplicar el fix del hook EN EL WORKTREE y commitearlo en `auto/*` — al mergear el PR, main heredara el fix.
b. Si el hook bloquea progreso y el fix del hook excede tu scope, `git commit --no-verify` para ESE commit SOLO, documentando excepcion en `task_runs.events_json[].decision="skip_hook"` con razon.
NO modificar archivos en main directamente.
11. **Post-iteracion sanity check**. Tras cada commit en `auto/*`, verificar:
```bash
git -C /home/lucas/fn_registry status --short
```
Si la salida cambia respecto al baseline (capturado al inicio del piloto), HAS contaminado el repo principal. ABORT con `status=sandbox_breach` y reporta los archivos afectados en el output al humano.
---
## Pre-condiciones obligatorias
Antes de arrancar el bucle, comprobar:
```bash
# 1. Migration 006_task_runs.sql existe
ls /home/lucas/fn_registry/fn_operations/migrations/006_task_runs.sql 2>/dev/null \
|| { echo "ABORT: migration 006_task_runs.sql ausente. Aplicar issue 0069 paso 1 antes."; exit 2; }
# 2. Subagentes fn-* presentes
for a in fn-constructor fn-executor fn-recopilador fn-analizador fn-mejorador; do
test -f /home/lucas/fn_registry/.claude/agents/$a/SKILL.md \
|| { echo "ABORT: subagente $a ausente"; exit 2; }
done
# 3. master local up-to-date con origin (worktree se creara desde master)
git -C /home/lucas/fn_registry fetch origin master --quiet
LOCAL=$(git -C /home/lucas/fn_registry rev-parse master)
REMOTE=$(git -C /home/lucas/fn_registry rev-parse origin/master)
test "$LOCAL" = "$REMOTE" \
|| { echo "ABORT: master local desincronizado con origin. git pull antes."; exit 2; }
# 4. Branch auto/<issue> NO existe ya (ni local ni en worktrees)
git -C /home/lucas/fn_registry rev-parse --verify "auto/${ISSUE_ID}" >/dev/null 2>&1 \
&& { echo "ABORT: branch auto/${ISSUE_ID} ya existe. Limpiar antes (git branch -D + worktree remove)."; exit 2; }
# 5. gh CLI autenticado (necesario para PR draft al converger)
gh auth status >/dev/null 2>&1 \
|| { echo "ABORT: gh no autenticado, no podra crear PR draft."; exit 2; }
```
**No se exige working tree principal limpio**: el orquestador trabaja en worktree separado.
Si alguna falla → reportar al main thread y salir. NO intentar continuar.
---
## Input
Recibes:
- `issue_id` (ej. `0070`) o `task_spec` inline (objetivo, criterios aceptacion).
- Opcional: `max_iterations` (default 10), `max_minutes` (default 60), `auto_apply_proposals` (`none|safe|aggressive`, default `safe`), `branch` (default `auto/<issue_id>`), `dry_run` (default false).
Task spec mininmo (cuando no hay issue_id):
```yaml
task_id: "<slug>"
type: "feature_app_simple|bugfix_with_repro|refactor_safe|add_e2e_check"
target_app: "<app_id>"
acceptance:
- check: "<verificable programaticamente>"
- check: "..."
```
**Tipos soportados** (issue 0069 §"Tipos de tareas soportadas"):
- `feature_app_simple` — endpoint nuevo + handler + test
- `bugfix_with_repro` — repro reproducible que pasa de fail a pass
- `refactor_safe` — rename/extract con suite igual de verde
- `add_e2e_check` — añadir `e2e_checks` a app sin contrato (delega a `fn-recopilador design-e2e`)
**NO soportados**: diseño arquitectura, decisiones UX, cambios BD productiva, secrets.
---
## Algoritmo
### 0. Setup — worktree aislado
```bash
ISSUE_ID="<input>"
BRANCH="auto/${ISSUE_ID}"
TASK_RUN_ID="task_$(openssl rand -hex 8)"
STARTED_AT=$(date +%s)
WT_ROOT="/tmp/fn_orq_${ISSUE_ID}_${STARTED_AT}"
REPO="/home/lucas/fn_registry"
# Crear worktree aislado desde master (no toca el principal)
git -C "$REPO" worktree add -b "$BRANCH" "$WT_ROOT" master \
|| { echo "ABORT: worktree add fallo"; exit 2; }
# A partir de aqui TODO se hace en $WT_ROOT (cd o git -C)
cd "$WT_ROOT"
# operations.db del app target. Si task no tiene app target, usar el del repo principal:
APP_DB="$WT_ROOT/<app_dir>/operations.db"
[ -f "$APP_DB" ] || APP_DB="$REPO/operations.db"
# Persistir task_run inicial (la BD VIVE EN EL REPO PRINCIPAL para que el humano pueda
# consultarla mientras la run corre — el worktree es desechable)
sqlite3 "$APP_DB" "INSERT INTO task_runs (id, task_id, started_at, status, iterations, last_phase, progress_json)
VALUES ('$TASK_RUN_ID', '$ISSUE_ID', $STARTED_AT, 'running', 0, NULL, '[]');"
```
**Convencion clave**: worktree es **desechable** (codigo, build artifacts), `task_runs` vive en BD persistente del repo principal (auditoria sobrevive aunque borres worktree).
### 1. Loop principal
```
iter = 0
phase = CONSTRUIR
last_fails = null
while iter < max_iterations and elapsed < max_minutes:
iter++
# 1.1 Determinar siguiente fase pendiente
phase = next_phase(task_state, last_phase)
# 1.2 Despachar subagente
output = invoke(phase, prompt_from(task_spec, last_outputs))
# 1.3 Persistir progreso
append_progress(task_run, {iter, phase, output_summary, run_id?})
# 1.4 Logica por fase
if phase == ANALIZAR:
if output.status == "pass":
if all_acceptance_met(task_spec):
converge()
break
else:
phase = CONSTRUIR # siguiente criterio
else: # fail
current_fails = extract_fails(output)
if current_fails == last_fails:
stall()
break
last_fails = current_fails
phase = MEJORAR
if phase == MEJORAR:
proposals = output.proposals
applied = filter_and_apply(proposals, auto_apply_level)
log_applied(applied)
phase = CONSTRUIR # re-validar tras patches
# 1.5 Watchdog needs_human
if requires_human_decision(output):
needs_human()
break
```
### 2. Despacho a subagentes
Usar `Agent` tool con `subagent_type` correcto. Prompt **autocontenido** (paths absolutos, IDs, criterio exito).
**CRITICO**: pasar `WT_ROOT` (worktree path) en cada prompt y exigir al subagente trabajar dentro de el. Subagentes NO deben tocar el repo principal `/home/lucas/fn_registry/`.
Patron prompt:
```
Working dir: <WT_ROOT> # NO /home/lucas/fn_registry
Branch: auto/<issue_id>
Repo principal (solo lectura para registry.db): /home/lucas/fn_registry
...
```
| Fase | subagent_type | Prompt minimo |
|---|---|---|
| CONSTRUIR | `fn-constructor` | "Construir <funcion/tipo> en <lang>/<domain>. Firma: <X>. Pureza: <pure/impure>. Tests obligatorios. Issue: <id>." |
| EJECUTAR | `fn-executor` | "Ejecutar <pipeline_id> con args <X> en <app_dir>. Registrar en operations.db." |
| RECOPILAR | `fn-recopilador` | "Auditar operations.db de <app_dir>. Reportar drift en JSON." |
| ANALIZAR | `fn-analizador` | "Validar <app_id>. Correr e2e_checks. Devolver run_id + status pass/fail + summary." |
| MEJORAR | `fn-mejorador` | "Procesar fallos de run_id=<X> en <app_id>. Crear proposals. Output --json." |
### 3. Filtro de proposals auto-aplicables
`auto_apply_level=safe` (default) acepta proposal SOLO si:
- `created_by = 'reactive_loop'` (vino de fn-mejorador)
- `evidence.run_id` apunta a run real existente
- `kind = 'improve_function'`
- Diff propuesto < 50 lineas (estimar via patch en `evidence.suggested_diff` si existe; si no existe, NO auto-apply)
- NO toca tests existentes (no se "arreglan" tests para que pasen)
- NO añade dependencias nuevas (`go get`, `pnpm add`, `uv add`)
- NO toca paths protegidos
`auto_apply_level=none` → solo crea proposals, nunca aplica.
`auto_apply_level=aggressive` → todas salvo `risk=high` o paths protegidos.
Aplicacion: delegar a `fn-constructor` con prompt "Aplicar proposal <id>. Diff sugerido: <X>. Verificar build despues."
### 4. Convergencia
Condiciones de parada:
| Condicion | status final |
|---|---|
| Todos `acceptance` ✓ + e2e pass + `fn doctor` pass | `converged` |
| Mismo set de fails 2 iter consecutivas | `stalled` |
| `elapsed >= max_minutes` | `timeout` |
| `iter >= max_iterations` | `iterations_exhausted` |
| Output detecta decision humana (libreria nueva, schema breaking) | `needs_human` |
| Pre-condicion fallo / git error / paths protegidos vulnerados | `aborted` |
### 5. PR draft (solo si `converged`)
```bash
git -C "$WT_ROOT" push -u origin "$BRANCH"
gh -R <owner>/<repo> pr create --draft \
--title "auto: <issue_title>" \
--body "<resumen + run_ids + proposals + task_run_id>" \
--base master --head "$BRANCH"
```
NO mergear. Devolver URL al main thread.
### 5.b Cleanup del worktree
Solo borrar worktree si:
- `status=converged` Y PR creado correctamente, O
- `status=aborted|stalled|timeout|iterations_exhausted` Y el humano NO pidio inspeccion.
```bash
# Default: NO borrar. Reportar comando para que humano decida.
echo "Worktree disponible en $WT_ROOT para inspeccion."
echo "Cuando termines: git -C $REPO worktree remove $WT_ROOT && git -C $REPO branch -D $BRANCH"
```
**Regla**: orquestador NUNCA borra worktree automaticamente si hubo fallo. Worktree = evidencia forense. Solo auto-cleanup en `converged` con PR creado.
```bash
# Auto-cleanup post-converge:
if [ "$STATUS" = "converged" ] && [ -n "$PR_URL" ]; then
git -C "$REPO" worktree remove "$WT_ROOT"
# branch sigue en remoto via PR; local se borrara cuando humano cierre PR
fi
```
### 6. Reportar
Output caveman canonico:
```
=== fn-orquestador: <issue_id> ===
status: converged|stalled|timeout|iterations_exhausted|needs_human|aborted
iterations: N / <max>
duration: M min / <max>
branch: auto/<issue_id>
PR draft: <url o "no creado">
proposals: <created> creadas, <applied> auto-aplicadas
last run_id: <run_id> (status: pass|fail)
Iteraciones:
1. construir → ok (3 funciones nuevas: id_a, id_b, id_c)
2. ejecutar → ok (run_id=exec_xxx)
3. analizar → fail (3/8 checks: build, smoke, tests)
4. mejorar → 3 proposals (2 safe-applied, 1 needs human)
5. construir → ok (re-build tras patches)
6. analizar → pass (8/8)
7. recopilar → ok (operations.db integra)
8. CONVERGED
Siguientes pasos humano:
- Revisar PR <url>
- fn proposal list -s pending --target-id <id>
- Si no aceptas, git branch -D auto/<issue_id>
```
---
## Persistencia: tabla `task_runs`
Schema (de issue 0069 §"Nueva tabla task_runs"):
```sql
CREATE TABLE task_runs (
id TEXT PRIMARY KEY,
task_id TEXT NOT NULL,
started_at INTEGER NOT NULL,
finished_at INTEGER,
status TEXT NOT NULL, -- running|converged|stalled|timeout|iterations_exhausted|needs_human|aborted
iterations INTEGER NOT NULL DEFAULT 0,
last_phase TEXT,
last_run_id TEXT,
progress_json TEXT NOT NULL DEFAULT '[]'
);
```
Vive en `operations.db` del app target (NO en registry.db). Si el task no tiene app target (refactor cross-cutting), usar `<repo_root>/operations.db` (excepcion documentada).
Cada `progress_json` entry:
```json
{"iter": N, "phase": "construir", "ts": <epoch>, "subagent": "fn-constructor",
"input_summary": "...", "output_summary": "...", "run_id": "..." }
```
---
## Reglas de comportamiento
1. **Briefing autocontenido** a cada subagente. Nunca asumir contexto compartido.
2. **Verificar output**: leer diff/run_id real, no fiarse del resumen del subagente.
3. **No paralelo dentro de una iteracion** (las fases son secuenciales). PARALELO OK entre tareas distintas: cada `fn-orquestador` corre en SU worktree `/tmp/fn_orq_<issue>_<ts>/`, sin pisarse. N orquestadores simultaneos = N worktrees + N branches `auto/<X>`, `auto/<Y>`.
4. **Caveman en stdout** del orquestador. Telemetry estructurada en `task_runs`.
5. **Stop > recovery**. Ante duda, abortar con `status=needs_human`, NO improvisar fixes.
6. **No tocar `.git` directamente** salvo `checkout`, `add`, `commit`, `push`. Nada de `reset --hard`, `rebase -i`, `branch -D`.
7. **Commits atomicos** por fase: `chore(auto): <fase> iter N — <descripcion corta>`. Co-authored por agente que ejecuto.
---
## Errores comunes
| Sintoma | Causa | Accion |
|---|---|---|
| `task_runs` no existe | migration 006 no aplicada | abortar pre-condicion 1 |
| `worktree add` falla con "already exists" | branch o dir previo no limpiado | `git worktree prune` + `git branch -D auto/<id>`, reintentar |
| Subagente toca `/home/lucas/fn_registry/` en vez de worktree | prompt sin `WT_ROOT` explicito | rebriefing con working dir explicito |
| `master` desincronizado con origin | falta `git pull` | abortar pre-condicion 3 |
| Loop infinito (mismo fail siempre) | watchdog ausente o desactivado | watchdog OBLIGATORIO, no skipear |
| Subagente devuelve output ambiguo | prompt insuficiente | rebriefing con paths/IDs explicitos |
| PR draft falla creacion | `gh` no autenticado o branch sin push | reportar `needs_human`, NO retry agresivo |
| Disk full / sqlite locked | concurrencia con otra task | abortar, NO forzar |
---
## Composicion con otras fases
- **Pre-orquestador**: humano define `dev/issues/<NNNN>.md` con criterios verificables programaticamente. Sin issue verificable, NO arrancar.
- **Durante**: orquestador despacha a las 5 fases. Cada subagente respeta SUS reglas (purity, registry-first, etc.).
- **Post-orquestador**: humano revisa PR draft + proposals. Acepta, modifica o descarta.
- **NO orquestes a otro `fn-orquestador`**. Una run no spawn-ea otra. Recursion = abort.
---
## Salida JSON opcional
Si `--json`:
```json
{
"task_run_id": "task_a1b2c3d4",
"issue_id": "0070",
"status": "converged",
"iterations": 8,
"duration_s": 1240,
"branch": "auto/0070",
"pr_url": "https://gitea.../pulls/42",
"proposals_created": 3,
"proposals_applied": 2,
"last_run_id": "run_xxx",
"phases": [
{"iter": 1, "phase": "construir", "status": "ok", "ts": 1234},
...
]
}
```
Util para integraciones (CI, dashboard, otra automatizacion). NO para spawn-ear otro orquestador.
---
## Limites duros
- `max_iterations`: 10 default, ceiling 30.
- `max_minutes`: 60 default, ceiling 240.
- Diff total por iteracion: 500 lineas. Si excede → `needs_human`.
- Proposals auto-aplicadas por run: 5. Si excede → resto a `pending`.
- Recursividad: 0. NO spawn de otro orquestador.
+1
View File
@@ -0,0 +1 @@
../../projects/aurgi/.claude/commands
+36
View File
@@ -0,0 +1,36 @@
---
description: "DEPRECADO 2026-05-19 — usa /autopilot. Wrapper directo a fn-orquestador conservado solo como debug primitive."
---
# /autonomous-task — DEPRECADO (sustituido por `/autopilot`)
**ESTADO:** deprecado 2026-05-19. Usa `/autopilot <NNNN>` en su lugar.
## Por que deprecado
`/autopilot` (v2, 2026-05-19) absorbe la funcionalidad y anade:
- Pre-flight DoD readiness check (gate STOP — no arranca sin DoD).
- Detector issue vs flow.
- Reporte estructurado al humano post-delegate.
- Self-Q&A migrado a fn-orquestador.
Behaviour orquestador-side es identico. La unica diferencia es que `/autopilot` valida antes de delegar; `/autonomous-task` delegaba ciego.
## Sustitucion 1:1
| Antes | Ahora |
|---|---|
| `/autonomous-task 0070` | `/autopilot 0070` |
| `/autonomous-task 0070 --max-iterations 15 --max-minutes 90` | `/autopilot 0070 --max-iterations 15 --max-minutes 90` |
| `/autonomous-task 0070 --dry-run` | `/autopilot 0070 --dry-run` |
| `/autonomous-task 0070 --auto-apply-proposals safe` | `/autopilot 0070 --auto-apply-proposals safe` |
## Modo debug
Si `/autopilot` falla en pre-flight pero quieres forzar dispatch sin DoD check (debug / experimentos), puedes seguir usando `/autonomous-task` que va directo a `fn-orquestador` sin validar. NO RECOMENDADO para uso normal.
## Migration deadline
Sin deadline duro — `/autonomous-task` seguira funcionando hasta que un commit lo elimine. Pero NO se anaden nuevas features aqui; cualquier mejora va a `/autopilot`.
Ver `.claude/commands/autopilot.md` para spec completa.
+212
View File
@@ -0,0 +1,212 @@
---
name: autopilot
description: Modo full-auto. Pre-flight DoD check, detecta issue vs flow, SIEMPRE delega a fn-orquestador (worktree aislado + PR Gitea). Sin Path inline. Sustituye a /autonomous-task.
---
# /autopilot — Comando autonomo unificado
Comando UNICO para ejecutar issue o flow autonomo end-to-end. Sustituye a `/autonomous-task` (deprecado). Hace dos cosas:
1. **Pre-flight DoD readiness check** — sin DoD claro, no arranca.
2. **Delega SIEMPRE a `fn-orquestador`** via Agent tool — worktree aislado en `/tmp/fn_orq_<NNNN>_<ts>/`, branch `auto/<NNNN>-<slug>`, PR draft Gitea al converger.
NO ejecuta nada inline. NO muta cwd del shell del humano. NO duplica worktrees. Toda la complejidad de bucle + paths protegidos + sanity check vive en `fn-orquestador`.
## Por que solo delegar
Historico: versiones anteriores de `/autopilot` tenian Path A (delegate a orquestador), Path B (registry-only inline), Path C (flow inline). Los Path B/C reimplementaban lo que ya hace `fn-orquestador` (worktree, branch, PR) y arrastraban un bug: `cd` en Bash de Claude Code PERSISTE entre llamadas → si autopilot hace `cd "$WT"`, todos los Bash subsiguientes operan en branch incorrecta. Solucion: NO hacer Path inline, delegar siempre.
`fn-orquestador` ahora soporta dos `task_type`:
- `issue` — flujo CONSTRUIR→EJECUTAR→RECOPILAR→ANALIZAR→MEJORAR (default).
- `flow` — parsea `dev/flows/<NNNN>-*.md` ## Flow y ejecuta steps (Path C absorbido).
## Sintaxis
```
/autopilot <NNNN> # issue NNNN (default si no hay prefijo)
/autopilot issue:<NNNN> # issue explicito
/autopilot i:<NNNN> # alias
/autopilot flow:<NNNN> # flow NNNN
/autopilot f:<NNNN> # alias
/autopilot check <target> # solo audita DoD readiness, no delega
/autopilot <target> --max-iterations N --max-minutes M --dry-run
```
Detector:
- `^\d{4}[a-z]?$` → issue (sin prefijo = issue por defecto).
- `^(issue|i):\d{4}[a-z]?$` → issue.
- `^(flow|f):\d{4}$` → flow.
- Otra cosa → ABORT con error de sintaxis.
## Pre-flight DoD readiness check (OBLIGATORIO)
Sin DoD claro, autopilot no delega. Verificacion es STOP-gate.
### Issue (`dev/issues/<NNNN>-*.md`)
1. Archivo existe en `dev/issues/` (no en `completed/`).
2. Frontmatter con `status`, `priority`.
3. Al menos UNA de:
- `## DoD` o `## Definition of Done` con >=1 bullet/checkbox concreto.
- `## Acceptance` con checkboxes `[ ]`.
- `## Tests` + `## Tareas` ambas no vacias.
4. Tipo declarado/inferible soportado por `fn-orquestador`: `feature_app_simple`, `bugfix_with_repro`, `refactor_safe`, `add_e2e_check`, `feature_registry_only`.
5. NO contiene criterios no-verificables ("queda bonito", "intuitivo", "UX mejor"). Grep simple; si match → ABORT con warning.
### Flow (`dev/flows/<NNNN>-*.md`)
1. Archivo existe en `dev/flows/`.
2. Frontmatter valido.
3. `## Acceptance` con >=1 checkbox.
4. `## Flow` no vacio.
5. Pre-requisitos declarados.
6. Tabla de funciones recomendadas sin `FALTA: crear <id>` (si los hay → ABORT salvo `--allow-construct-missing`).
Si falla:
```
=== /autopilot check 0125 ===
status: NOT READY
target: issue 0125 (skill-tree-dashboard-panel)
gaps:
- Sin seccion DoD/Acceptance
- "UX intuitiva" linea 47 — no verificable
fix:
- Anadir ## DoD con 3-5 bullets programaticamente verificables
- Reemplazar criterios subjetivos por mediciones concretas
```
Si OK:
```
=== /autopilot check 0107c ===
status: READY
target: issue 0107c (refactor data_table)
dod_items: 5 checkboxes
task_type: refactor_safe
estimated_iter: 3-5
```
## Dispatch a fn-orquestador
Tras pre-flight OK, ejecuta:
```
Agent(
subagent_type="fn-orquestador",
prompt="""
Issue/Flow: <path al .md>
Modo: REAL (o --dry-run)
task_type: <issue|flow>
Pre-condiciones verificadas: 7/7 verde
Master: <sha> sync con origin
Working tree principal: limpio (baseline)
Max iter: N
Max min: M
Auto-apply proposals: safe
Token Gitea: pass gitea/dataforge-git-token
DB task_runs: apps/deploy_server/operations.db (schema task_id)
Reglas duras: autonomous_loop.md (11 reglas)
""",
run_in_background=true
)
```
Cuando termine, reporta al humano con output canonico del orquestador:
```
=== /autopilot 0121b ===
target: issue 0121b (fn doctor e2e-coverage)
delegated_to: fn-orquestador
status: converged
iterations: 1 / 8
duration: 4 min / 30
task_run_id: task_d285372493cce2e6
branch: auto/0121b-orquestador
worktree: /tmp/fn_orq_0121b_1779147778
PR draft: https://gitea-.../dataforge/fn_registry/pulls/3
Siguiente: revisar PR, mergear, mover issue a completed/
```
## Reglas duras (autopilot-level)
1. **Cero cwd mutation**. Autopilot NUNCA hace `cd`. Usa `git -C <repo>` siempre si necesita inspeccionar.
2. **Cero ejecucion inline de bucle**. Todo va via `fn-orquestador`. Si autopilot necesita ejecutar algo (pre-flight scripts), es read-only.
3. **Cero AskUserQuestion**. Self-pick "Recommended". Si no hay, ABORT con `status=needs_human`.
4. **DoD es contrato**. Si DoD no se cumple al final, `task_run.status` queda `partial` y autopilot reporta NOT_DONE — humano decide.
5. **Worktree gestion delegada al orquestador**. Autopilot NO crea worktrees propios. NO toca branches.
6. **Trazabilidad**: cada decision pre-delegate (especialmente abort de DoD check) se persiste en `task_runs.events_json[]` con `agent: autopilot`.
## Flags
| Flag | Default | Que hace |
|---|---|---|
| `--max-iterations N` | 10 | Pasado al orquestador |
| `--max-minutes M` | 60 | Pasado al orquestador |
| `--dry-run` | off | Pasado al orquestador |
| `--allow-construct-missing` | off | Flow con `FALTA: crear <id>` → spawn fn-constructor antes |
| `--auto-apply-proposals` | `safe` | Pasado al orquestador |
## Errores canonicos
| Codigo | Significado | Accion |
|---|---|---|
| `NOT_READY` | DoD insuficiente | Humano edita .md y relanza |
| `needs_human` | Decision ambigua | Humano resuelve y relanza |
| `delegated_failed` | fn-orquestador devolvio fail/stall/timeout | Humano lee `task_runs.events_json` |
| (resto) | Heredados del orquestador (stalled/timeout/aborted_protected_path/...) | Idem |
## Anti-patrones
| Anti-patron | Por que es malo |
|---|---|
| Hacer Path B/C inline | Mismo bug de cwd mutation que paso 2026-05-19 |
| Saltar pre-flight DoD | Trabajar sin contrato = bucle infinito |
| Mergear sin tests verde | fn-orquestador ya impide esto, NO bypaseas |
| `AskUserQuestion` desde autopilot | Rompe contrato autonomo |
| Crear worktree propio en autopilot | Duplica + colision con orquestador (paso 2026-05-19) |
## Ejemplos
```bash
# Issue con DoD claro
/autopilot 0107c
# Flow con piezas faltantes — autoriza creacion antes
/autopilot flow:0008 --allow-construct-missing
# Solo audit
/autopilot check 0125
/autopilot check flow:0008
# Dry run
/autopilot 0107c --dry-run
```
## Relacion con otras reglas
- [[autonomous_loop]] — politica del bucle (sandbox, paths protegidos, watchdog). fn-orquestador la aplica.
- [[apps_tbd]] — politica TBD por tipo de cambio.
- [[apps_subrepo]] — `git init` dentro de apps nuevas antes de limpiar worktree.
- [[feature_flags]] — codigo incompleto detras de flag OFF.
- [[registry_calls]] — invocaciones canonicas.
- [[e2e_validation]] — `e2e_checks` consumidos por fn-analizador.
- [[delegation]] — spawn fn-constructor antes que escribir inline.
## Migracion desde `/autonomous-task`
`/autonomous-task` queda DEPRECADO. Sustitucion 1:1:
| Antes | Ahora |
|---|---|
| `/autonomous-task 0070` | `/autopilot 0070` |
| `/autonomous-task 0070 --max-iterations 15` | `/autopilot 0070 --max-iterations 15` |
| `/autonomous-task 0070 --dry-run` | `/autopilot 0070 --dry-run` |
`/autopilot` anade pre-flight DoD check + detect flow. Behaviour orquestador-side idem.
## Historico
- v1 (2026-05-15): introducido con Path A/B/C inline + self-Q&A.
- v2 (2026-05-19): simplificado tras incidente cwd mutation en piloto 0121b. Solo delega a fn-orquestador. Self-Q&A movido al orquestador. Sustituye a `/autonomous-task`.
+86
View File
@@ -0,0 +1,86 @@
---
description: "Lista todos los slash commands disponibles en el repo: globales de fn_registry + namespaced de cada project. Filtra por substring o por namespace."
---
# /commands — Catalogo de slash commands del repo
Inventario unificado. Lista los `.md` bajo `.claude/commands/` (recursivo, sigue symlinks) y agrupa por namespace.
## Sintaxis
```
/commands # listado completo agrupado por namespace
/commands <substring> # filtra por substring en nombre o descripcion
/commands --ns <namespace> # solo un namespace (global, aurgi, ...)
/commands --json # salida JSON para agentes
```
## Implementacion
Bash + awk. Parsea frontmatter `description:` de cada `.md`. Agrupa por subdirectorio (subdir = namespace, root = `global`).
```bash
#!/usr/bin/env bash
set -euo pipefail
ROOT="${FN_REGISTRY_ROOT:-/home/egutierrez/fn_registry}"
CMD_DIR="$ROOT/.claude/commands"
# Recolecta: ns|name|description
collect() {
find -L "$CMD_DIR" -type f -name '*.md' | while read -r f; do
rel="${f#$CMD_DIR/}"
case "$rel" in
*/*) ns="${rel%%/*}"; name="${rel#*/}"; name="${name%.md}" ;;
*) ns="global"; name="${rel%.md}" ;;
esac
desc=$(awk '/^description:/ {sub(/^description:[[:space:]]*/, ""); gsub(/^"|"$/, ""); print; exit}' "$f")
printf '%s|%s|%s\n' "$ns" "$name" "${desc:-(sin descripcion)}"
done | sort
}
collect | awk -F'|' '
{
if ($1 != prev_ns) {
if (prev_ns) print ""
if ($1 == "global") print "## global (/<cmd>)"
else print "## " $1 " (/" $1 ":<cmd>)"
prev_ns = $1
}
printf "- /%s%s — %s\n", ($1=="global"?"":$1":"), $2, $3
}'
```
Filtros:
- Substring: `grep -i "<substring>"` sobre stdout.
- `--ns X`: filtrar antes del `awk` por `$1 == "X"`.
- `--json`: reemplazar el `awk` por `jq -Rsn` que construya array `{namespace, name, description, invocation}`.
## Salida (formato humano)
```
## global (/<cmd>)
- /app — Crear, configurar y desplegar apps del registry
- /autopilot — Modo full-auto...
- /commands — Catalogo de slash commands del repo
...
## aurgi (/aurgi:<cmd>)
- /aurgi:anadir_contexto_aurgi — Anade o modifica contexto...
- /aurgi:aumentar_task — Enriquece tarea Aurgi con preguntas...
- /aurgi:contexto_aurgi — Aprende el contexto de Aurgi...
```
## Cuando usarlo
- Sesion nueva: ver de un vistazo que slash commands hay disponibles.
- Antes de inventar logica inline: comprobar si ya existe un command.
- Auditoria: verificar que los projects exponen sus commands correctamente.
- Onboarding: nuevo PC clonado, descubrir capacidades del repo sin abrir N archivos.
## Gotchas
- Sigue symlinks (`find -L`). Si un symlink apunta a directorio inexistente, devuelve vacio para esa rama — verificar con `ls -L .claude/commands/<ns>/`.
- Solo escanea `<root>/.claude/commands/`. Commands user-global en `~/.claude/commands/` NO entran (son personales, fuera del repo).
- Namespace = nombre del subdirectorio bajo `.claude/commands/`. Coincide con el project pero no por mecanismo — por convencion. Ver `.claude/rules/project_commands.md`.
- Para que un command de project aparezca aqui desde la raiz, hace falta el symlink (`.claude/commands/<project>` -> `../../projects/<project>/.claude/commands`).
+274
View File
@@ -0,0 +1,274 @@
# /cpp-app — Crear o modificar app C++ del registry sin olvidar nada
Recopila TODOS los datos necesarios (frontmatter, trio app_hub, panels, AppConfig, service block, e2e_checks, uses_functions) **antes** de tocar el disco. Tras confirmar, ejecuta scaffolder o edits, regenera iconos, refresca app_hub, compila y deploya a Windows.
Sustituye al flujo manual "edito main.cpp + app.md + CMakeLists.txt a mano". Wrapper sobre `init_cpp_app_bash_pipelines` (create) o edits directos sobre `app.md` (modify) + `regenerate_app_icons` + `refresh_app_hub` + `redeploy_cpp_app_windows`.
---
## Uso
```
/cpp-app # interactivo, modo create
/cpp-app <name> # interactivo, modo create con name pre-rellenado
/cpp-app modify <name> # editar app existente
```
---
## Modo CREATE — flujo turno a turno
Si `$ARGUMENTS` no empieza por `modify`, es create. Si trae `<name>`, lo usas como default; si no, pregunta name.
### Paso 0 — verificar que no existe
```bash
test -d "/home/lucas/fn_registry/apps/<name>" \
|| ls /home/lucas/fn_registry/projects/*/apps/<name> 2>/dev/null
```
Si existe en cualquier ubicacion: **abortar** y sugerir `/cpp-app modify <name>`. NO sobreescribir.
### Paso 1 — Identidad (AskUserQuestion)
1. **name** (texto libre — valida snake_case + contiene verbo segun `ids_naming.md`). Verbos canonicos: `show, render, view, plot, edit, manage, monitor, browse, explore, run, launch, scan, audit, debug, profile, ...`. Si no trae verbo, sugerir alternativas (`viewer` -> `<name>_viewer`).
2. **project** (select: ninguno / lista de `projects/*/`). Si ninguno -> `apps/<name>/`.
3. **domain** (select: `tools` (default), `gfx`, `tui`, `infra`, `finance`, `datascience`, `cybersecurity`, `shell`, `pipelines`, `browser`).
4. **description** 1 linea (texto libre, max 80 chars). **OBLIGATORIO** — sin esto el hub muestra tarjeta vacia.
### Paso 2 — Trio app_hub OBLIGATORIO
Regla dura `cpp_apps.md`: description + icon.phosphor + icon.accent SIEMPRE juntos.
5. **icon.phosphor** glyph name. Antes de preguntar, ofrece busqueda:
```bash
ls /home/lucas/fn_registry/sources/phosphor-core/assets/fill/ | grep -i "<keyword>"
```
Sugiere 3-5 candidatos basados en `description`. Default segun domain: `gfx`->`palette`, `tui`->`terminal`, `tools`->`wrench`, `infra`->`gear`, `finance`->`chart-line-up`, `datascience`->`graph`, `cybersecurity`->`shield`.
6. **icon.accent** hex `#rrggbb` (palette select):
- sky `#0ea5e9`, indigo `#4f46e5`, violet `#7c3aed`, pink `#ec4899`, rose `#f43f5e`, red `#dc2626`, orange `#ea580c`, amber `#d97706`, green `#16a34a`, teal `#0d9488`, cyan `#0891b2`, slate `#475569`. Default segun domain.
### Paso 3 — Tags
7. **tags** (multiSelect): `service`, `launcher`, `dashboard`, `viewer`, `editor`, `monitor`, `debug`, `prototype`. Si selecciona `service` -> activar bloque service (Paso 7).
### Paso 4 — Panels iniciales
8. **panels** (texto libre o select):
- Default: 1 panel `Main` (Ctrl+1).
- Opcion lista: hasta 4 paneles. Por cada uno: `{label, shortcut}`. Generara `PanelToggle k_panels[]` en `main.cpp`.
### Paso 5 — AppConfig flags
9. (multiSelect):
- `init_gl_loader` (true si la app llama `gl*` directo, ej. shaders, GPU renderer custom). Default false.
- `viewports` true (default) / false (single-window).
- `auto_dockspace` true (default) / false (solo si gestiona DockSpace propio tipo `shaders_lab`).
- `fps_overlay` activo de inicio? (controla solo el default; el menu Settings lo toggle).
### Paso 6 — Funciones del registry a usar
10. **uses_functions** lista IDs. Antes de preguntar, busca candidatas segun description:
```
mcp__registry__fn_search query="<keyword>" entity="functions"
```
Y muestra capability groups relevantes (`docs/capabilities/INDEX.md`). El usuario puede aceptar lista, anadir IDs, o dejar vacio (se rellena tras codear).
Cada ID que no este en el registry -> ofrecer spawn `fn-constructor` antes de continuar (regla `delegation.md`).
### Paso 7 — Bloque `service:` (solo si tag=service)
11. Si paso 3 marco `service`, recopilar (regla `function_tags.md` + issue 0105):
- `port` int o null
- `health_endpoint` ruta GET o null
- `health_timeout_s` (default 3)
- `runtime` (select: `systemd-user`, `systemd-system`, `docker-compose`, `stdio`, `manual`)
- `systemd_unit` (obligatorio si runtime empieza por `systemd-`)
- `systemd_scope` (`user|system|null`)
- `restart_policy` (select: `always` (Recommended — gotcha: `on-failure` NO reinicia SIGTERM limpio), `on-failure`, `none`)
- `pc_targets` (multiSelect de pc_locations actuales: `aurgi-pc`, `home-wsl`, ...)
- `is_local_only` (true/false default false)
### Paso 8 — Persistencia
12. (multiSelect):
- BD propia SQLite `<name>.db` en `local_files/`? -> recordar usar `fn::local_path("<name>.db")` (cpp_apps.md §7)
- operations.db (para entities/relations)? -> ejecutar `fn ops init` tras crear
- Archivos config en `local_files/`?
### Paso 9 — e2e_checks (issue 0068)
13. Default sugerido (modificable):
```yaml
e2e_checks:
- id: build
cmd: "cmake --build cpp/build --target <name> -j"
timeout_s: 300
- id: self_test
cmd: "./cpp/build/apps/<name>/<name> --self-test"
timeout_s: 30
severity: warning # si todavia no implementa --self-test
```
Pregunta: ¿anadir mas checks (ops_audit, pytest, smoke)?
### Paso 10 — Resumen y confirmacion
Mostrar bloque YAML completo del `app.md` que se va a generar + flags del scaffolder + post-acciones. Pedir confirmacion antes de ejecutar.
---
## Modo CREATE — ejecucion
Una vez confirmado:
```bash
cd /home/lucas/fn_registry
# 1. Scaffolder
./fn run init_cpp_app <name> \
[--project <p>] \
[--domain <d>] \
--desc "<description>" \
[--tags "<csv>"]
# 2. Editar app.md generado para anadir:
# - icon: {phosphor, accent}
# - service: {...} (si aplica)
# - uses_functions: [...]
# - e2e_checks: [...]
# (el scaffolder no rellena estos; editarlos con Edit tool)
# 3. Editar main.cpp generado para reflejar:
# - panels[] custom (si != default)
# - cfg.init_gl_loader / cfg.auto_dockspace / cfg.viewports
# - includes de funciones registry usadas
# 4. Editar CMakeLists.txt para anadir paths de funciones del registry:
# ${CMAKE_SOURCE_DIR}/functions/<d>/<f>.cpp
# 5. Si es service -> ofrecer crear systemd unit (skipear si runtime=stdio|manual)
# 6. Si pidio operations.db
./fn ops init apps/<name> # o projects/<p>/apps/<name>
# 7. Generar icono
./fn run generate_app_icon "<phosphor>" "<accent>" "<dir>/appicon.ico"
# 8. Indexar
./fn index
# 9. Compilar Windows
./fn run redeploy_cpp_app_windows <name> <dir> --build
# 10. Refrescar app_hub
./fn run refresh_app_hub
# 11. Auditoria
./fn doctor cpp-apps
[[ "<tag>" == *service* ]] && ./fn doctor services-spec
```
---
## Modo MODIFY — flujo
`/cpp-app modify <name>`
### Paso 0 — Localizar
```bash
# Buscar apps/<name>/ o projects/*/apps/<name>/
sqlite3 /home/lucas/fn_registry/registry.db \
"SELECT id, dir_path FROM apps WHERE name='<name>' AND lang='cpp';"
```
Si no existe: abortar, sugerir `/cpp-app` (sin args) para crear.
### Paso 1 — Mostrar config actual
```bash
mcp__registry__fn_show id="<id>"
cat <dir>/app.md
```
### Paso 2 — Que cambiar (multiSelect)
- `description` (1 linea)
- `icon.phosphor` o `icon.accent`
- `tags` (anadir/quitar; si toca `service` -> Paso 7 del create)
- `uses_functions` (anadir/quitar — recordar editar CMakeLists.txt)
- `panels` (anadir/quitar/renombrar)
- `service:` block (si tag=service)
- `e2e_checks`
- `domain`
- `rename` (cambia name, dir, IDs derivados, repo Gitea — operacion delicada, requiere doble confirmacion)
### Paso 3 — Aplicar cambios
Para cada cambio: usa `Edit` sobre los archivos correspondientes. NUNCA `Write` completo de `app.md` (preserva campos que no toques).
### Paso 4 — Post-acciones (segun lo que toco)
```bash
# Siempre
cd /home/lucas/fn_registry && ./fn index
# Si toco icon.* -> regenerar appicon
./fn run generate_app_icon "<phosphor>" "<accent>" "<dir>/appicon.ico"
# Si toco trio o panels o uses_functions o cambia code:
./fn run redeploy_cpp_app_windows <name> <dir> --build
# Si toco description o icon o tags:
./fn run refresh_app_hub
# Si toco service: o tag service
./fn doctor services-spec
# Siempre al final
./fn doctor cpp-apps
```
---
## Reglas duras
- **NUNCA** crear `main.cpp` + `CMakeLists.txt` + `app.md` a mano. Siempre via `init_cpp_app_bash_pipelines` (regla `cpp_apps.md`).
- **NUNCA** poner el codigo en `cpp/apps/<n>/`. Solo `apps/<n>/` o `projects/<p>/apps/<n>/`.
- **NUNCA** dejar `app.md` sin el trio (description + icon.phosphor + icon.accent). Tarjeta del hub queda gris.
- **NUNCA** declarar funciones del registry en `uses_functions` sin listar su `.cpp` en `CMakeLists.txt` (drift detectado por `fn doctor uses-functions`).
- **NUNCA** usar `Restart=on-failure` en systemd unit de un service C++ — gotcha 2026-05-17 (`sqlite_api.service` cayo 20h). Default `Restart=always`.
- Despues de **cualquier** cambio en el trio: `regenerate_app_icons <name>` + `refresh_app_hub`.
---
## Auto-verificacion final
Tras crear o modificar, reportar al usuario:
```
=== app <name> ===
dir: <abs_dir>
domain: <d>
description: "<desc>"
icon: <phosphor> + <accent>
tags: [<csv>]
uses_functions: N funciones (<list_top_5>)
panels: N (<labels>)
e2e_checks: N checks
service: <si/no — port:<p> health:<h>>
Acciones ejecutadas:
[✓] scaffolder / edits
[✓] generate_app_icon
[✓] fn index (registry.db actualizado)
[✓] redeploy_cpp_app_windows (Desktop/apps/<name>/<name>.exe)
[✓] refresh_app_hub (tarjeta visible en hub)
[✓] fn doctor cpp-apps (limpio | N warnings)
Siguiente paso sugerido:
- Abrir app_hub_launcher en Windows y verificar tarjeta
- Anadir tests visuales si la app tiene paneles propios (cpp/PATTERNS.md §11)
```
$ARGUMENTS
+186
View File
@@ -0,0 +1,186 @@
---
name: fix-issue
description: Implementar un issue de dev/issues/ end-to-end. Crea rama, ejecuta tareas, bumpa version si toca modulos/framework/apps (via /version), tests, cierra issue, integra a master.
---
# /fix-issue
Ejecuta el flujo completo de implementacion/cierre de un issue de `dev/issues/`. Adaptado al stack del registry: Go (`-tags fts5 CGO_ENABLED=1`), Python (`python/.venv/bin/python3`), Bash, TypeScript (`pnpm`), C++ (`cmake`+`mingw-w64` toolchain).
## Inputs
```
/fix-issue <NNNN[a|b|c...]>
```
- `NNNN`: numero del issue (ej. `0107`).
- Si es sub-issue, sufijo letra: `0107a`, `0107b`, ...
Si no se proporciona, preguntar.
## Flujo obligatorio
### 1. Resolver el issue
- `dev/issues/<NNNN>-*.md` → si no existe, STOP.
- Si ya en `dev/issues/completed/`, STOP.
- Si es sub-issue, leer tambien el principal para contexto.
### 2. Leer y extraer
- Objetivo, tareas, arquitectura, prerequisitos, riesgos.
- Identificar archivos afectados — anotar si toca:
- `modules/<X>/` o `cpp/framework/` → bumpa version (paso 8).
- `functions/`, `python/functions/`, `bash/functions/`, `frontend/functions/` → indexer + `fn index` al cerrar.
- Apps en `apps/<X>/` o `projects/*/apps/<X>/` → requiere rama TBD (regla `apps_tbd.md`) **+ bumpa version per-app (paso 8)**. Si el issue toca multiples apps, una llamada `/version` por app.
- Registry meta (CLAUDE.md, rules, templates) → push directo a master OK.
### 3. Estrategia de rama
**Registry-only changes** (functions/types/docs/rules):
- Push directo a master OK. NO crear rama.
**Apps changes** (apps/, projects/*/apps/):
- Crear rama TBD:
```bash
git checkout master
git pull --rebase
git checkout -b issue/<NNNN>-<slug>
```
La rama es del registry. Si la app es sub-repo, ademas crear rama dentro del sub-repo.
**Modules/framework changes** (`modules/`, `cpp/framework/`):
- Rama TBD obligatoria (afecta a todas las apps que linkean).
### 4. Plan con TaskCreate
- Crear tarea por bloque logico del issue.
- Incluir SIEMPRE:
- Tarea de tests (unit + smoke).
- Tarea de `fn index` si toco metadata.
- Tarea de `/version` si toco `modules/`, `cpp/framework/`, `apps/<X>/` o `projects/*/apps/<X>/` (una llamada por target).
- Tarea de cleanup/docs.
### 5. Implementar
Reglas registry-first (CLAUDE.md):
- ANTES de escribir codigo reutilizable → `mcp__registry__fn_search` para encontrar lo que existe.
- Si falta funcion reutilizable → spawn `fn-constructor` (no escribir inline).
- Si patron se repite >2x → propose nueva funcion.
- NUNCA `sqlite3 registry.db "SELECT ..."` plano — usar MCP.
Convenciones del stack:
| Stack | Build/test |
|---|---|
| Go | `CGO_ENABLED=1 go build -tags fts5 -o fn ./cmd/fn/` y `CGO_ENABLED=1 go test -tags fts5 ./...` |
| Python | `python/.venv/bin/python3 -m pytest <path>` |
| Bash | `bash -n <script>.sh` + tests inline |
| TypeScript | `cd frontend && pnpm build && pnpm test` |
| C++ (Linux) | `cmake --build build --target <app>` |
| C++ (Windows MinGW) | `cmake -B build/windows -DCMAKE_TOOLCHAIN_FILE=cpp/toolchains/mingw-w64.cmake && cmake --build build/windows --target <app>` |
Commits atomicos por bloque logico con prefijos: `feat:`, `fix:`, `test:`, `docs:`, `refactor:`, `chore:`. Mensajes en espanol. NO WIP.
### 6. Tests
Stack-dependent (ver arriba). Si tests pasan parcialmente con failures pre-existentes no causadas por la rama, documentar en cuerpo del commit/PR.
### 7. Feature flags (si aplica)
Si el issue forma parte de un feature multi-issue:
- Editar `dev/feature_flags.json` con el flag (desactivado).
- Activar el flag en el ultimo sub-issue del set.
Flag != WIP. Codigo detras de flag debe compilar + testear.
### 8. Version bump (si toco modulos/framework/apps)
**OBLIGATORIO si el issue toco** alguno de:
- `modules/<X>/` → bumpa `modules/<X>/module.md::version`.
- `cpp/framework/` → bumpa `modules/framework/module.md::version`.
- `apps/<X>/` → bumpa `apps/<X>/app.md::version`.
- `projects/<P>/apps/<X>/` → bumpa `projects/<P>/apps/<X>/app.md::version`.
```
/version <path> <major|minor|patch> "<reason>"
```
Reglas (modulos/framework):
- Major: breaking ABI/API publica.
- Minor: additive (nuevo helper, refactor interno sin cambio de API, nuevo miembro).
- Patch: bugfix puro.
Reglas (apps):
- Major: breaking observable (CLI args, schema BBDD propia, formato wire).
- Minor: feature aditiva visible (nuevo panel, endpoint, opcion).
- Patch: bugfix sin cambio observable, refactor interno, mejora perf.
**Una llamada `/version` por target afectado**. Si el issue toca 1 modulo + 2 apps -> 3 llamadas a `/version` (cada una con su `reason` y bump-type apropiado; pueden diferir).
Diff guard: cambios que solo tocan el `app.md` (correccion typo descripcion, anadir tag) NO requieren bump — son metadata, no comportamiento. Detectar con `git diff --name-only | grep -v '\.md$'` para decidir si hay cambio de codigo real.
`/version` solo edita + stage. NO commit. El bump va junto con el codigo correspondiente en el mismo commit (`feat:` o `fix:` o `refactor:`).
Si NO toco modulos/framework/apps, saltar este paso.
### 9. Cerrar el issue
Mover archivo:
```bash
mv dev/issues/<NNNN>-<slug>.md dev/issues/completed/
```
Actualizar `dev/issues/README.md`:
- Link → `completed/<NNNN>-<slug>.md`
- Estado → `completado`
Si es feature multi-issue y este es el ultimo sub-issue:
- Flip flag en `dev/feature_flags.json` a `enabled: true` con `enabled_at: <YYYY-MM-DD>`.
- Verificar que todos los sub-issues estan en `completed/`.
### 10. Integrar
**Registry-only changes**: push directo a master.
**Apps/modules/framework changes**: `/full-git-push` o `/git-push` (merge --no-ff de la rama a master, push, delete rama).
### 11. Verificar post-cierre
- `fn index` — registry.db al dia.
- `fn doctor` (subcomandos relevantes: `artefacts`, `services`, `cpp-apps`, `uses-functions`).
- Si toco modulos: `fn doctor modules` (post 0107a) — 0 drift.
## Reglas criticas
- **Registry-first**: SIEMPRE buscar antes de escribir; delegar a `fn-constructor` antes que inline.
- **TBD para apps**: NUNCA push directo a master en apps. Rama corta, merge --no-ff.
- **TBD NO para registry**: push directo OK para functions/types/docs/rules.
- **`/version` obligatorio** si tocas modulos, framework o apps (con cambio de codigo real, no solo metadata). Si no, drift entre `version:` y `## Capability growth log` y se pierde trazabilidad.
- **Tests siempre**: no cerrar issue sin tests pasando (salvo failures pre-existentes documentados).
- **Commits atomicos**: 1 commit = 1 bloque logico. No mezclar `feat:` + `test:` en mismo commit.
- **Cerrar siempre**: nunca dejar issue implementado sin mover a `completed/` + actualizar README.
## Referenciado desde
- `.claude/commands/version.md` — bump semver de modulos.
- `.claude/commands/full-git-push.md` — push del registry + sub-repos.
- `.claude/rules/apps_tbd.md` — politica de TBD por tipo de cambio.
## Ejemplo: implementar 0107c (refactor data_table)
```
/fix-issue 0107c
1. Resolver: dev/issues/0107c-split-data-table.md ✓
2. Extraer: refactor 4777 LOC → 6 sub-funciones. Toca modules/ → /version obligatorio.
3. Rama: issue/0107c-split-data-table desde master.
4. Plan: 8 tareas (lectura + 6 sub-funciones + entrypoint thin + version bump).
5. Implementar: spawn fn-constructor en paralelo si hay >1 sub-funcion independiente.
6. Tests: build + smoke + primitives_gallery --capture diff.
7. Flag: parte de modules-v2, NO activar todavia (espera 0107a-f cerrar).
8. /version modules/data_table major "split data_table.cpp into 6 sub-functions"
9. Cerrar: mv → completed/ + README.
10. /git-push.
11. fn index + fn doctor modules → 0 drift en consumidores limpiados.
```
+131
View File
@@ -0,0 +1,131 @@
---
description: "Gestiona flows (casos de uso multi-app reutilizables) en dev/flows/. Subcomandos: create, list, show, status, done. Runner automatizado en fase 2."
---
# /flow — Gestionar flows del registry
Flows = casos de uso end-to-end que prueban / ejercitan el sistema multi-app. Viven en `dev/flows/NNNN-<slug>.md`. Cada flow describe Goal + Flow steps + Acceptance checkboxes + Telemetria.
**OBLIGATORIO antes de `create`**: lee `dev/flows/AGENT_GUIDE.md`. Define donde buscar piezas (capability groups, FTS por tag, apps existentes, vaults), reglas duras para no inventar IDs, y plantilla de razonamiento para recomendar extractor / transformer / sink / scheduler / notify por flow.
Cada flow nuevo cita IDs reales del registry. Si una pieza falta, escribir `FALTA: crear <id>` en la tabla correspondiente. Nada de inventar nombres.
Diferencia con `dev/issues/`:
- Issues = bugs / features de implementacion.
- Flows = trabajos reutilizables que cruzan varias apps.
## Sintaxis
```
/flow create <slug> # nuevo flow desde template, ID auto
/flow list # tabla resumen
/flow show <NNNN> # imprime contenido + acceptance %
/flow status <NNNN> # status + acceptance % + ultima run
/flow done <NNNN> [--notes "..."] # cierra flow (status=done, mueve a completed/)
/flow run <NNNN> # fase 2 — runner automatizado (NO IMPLEMENTADO)
```
## Implementacion por subcomando
### `create <slug>`
Pasos:
1. Valida `<slug>` es kebab-case: `^[a-z][a-z0-9-]*$`. Si no, error.
2. Comprueba que no existe ya: `ls dev/flows/*-<slug>.md`. Si existe, error.
3. Calcula siguiente ID libre:
- `ls dev/flows/*.md dev/flows/completed/*.md | grep -oE '^dev/flows/(completed/)?[0-9]{4}' | sort -u | tail -1`
- Suma 1, zero-pad a 4 digitos.
4. Lee `dev/flows/template.md`.
5. Sustituye `<slug>`, `NNNN`, `YYYY-MM-DD` (hoy).
6. Escribe `dev/flows/NNNN-<slug>.md`.
7. Append fila a `dev/flows/INDEX.md` (mantener orden por ID asc).
8. Reporta path nuevo + recordatorio "edita Goal / Flow / Acceptance".
### `list`
Lee `dev/flows/INDEX.md` y lo imprime tal cual. Si flag `--pending` solo pending, `--done` solo done, `--app <name>` filtra por app.
Tambien anade columna `Accept%` calculada desde body:
- Para cada flow .md, cuenta `[ ]` y `[x]` en seccion `## Acceptance`.
- `% = checked / total * 100` redondeo entero.
### `show <NNNN>`
`cat dev/flows/NNNN-*.md` (busca con glob NNNN-*). Si no existe, prueba `dev/flows/completed/NNNN-*.md`. Si no, error.
### `status <NNNN>`
Imprime resumen del frontmatter + acceptance %:
```
=== flow 0001 ===
name: hn-top-stories
status: pending
risk: low
priority: high
apps: navegator_dashboard, dag_engine, data_factory, agents_and_robots
acceptance: 2/6 (33%)
updated: 2026-05-16
Pending checks:
- [ ] Recipe creada y validada
- [ ] DAG corre OK 2 veces consecutivas via scheduler
- [ ] data_factory.runs tiene >=2 entries
- [ ] Schema extraido cubre 6/6 fields
```
### `done <NNNN> [--notes "..."]`
Pasos:
1. Verifica todos los `[ ]` estan checked. Si no, prompt "X checks pendientes, --force para cerrar igualmente".
2. Edita frontmatter: `status: done`, `updated: <hoy>`.
3. Si `--notes`, append a seccion `## Notas`.
4. `git mv dev/flows/NNNN-<slug>.md dev/flows/completed/`.
5. Actualiza `dev/flows/INDEX.md`: cambia status del flow + mueve fila a seccion Completed (mantener tabla principal solo con pending/running/failed/deferred).
### `run <NNNN>` — FASE 2 (NO IMPLEMENTADO AUN)
Hoy: imprime `/flow run no implementado todavia. Sigue los pasos manualmente y marca acceptance con sed/edit.`
Diseño futuro:
- Parsea `## Flow` en pasos.
- Cada paso tipo `function: <id>` -> ejecuta `./fn run <id>`.
- Cada paso tipo `cmd: <bash>` -> ejecuta subprocess.
- Texto libre -> "MANUAL: <text>" + pause user input.
- Persistencia ejecuciones en `dev/flows/runs/<id>-<timestamp>.jsonl`.
- Update acceptance checkboxes automaticamente segun heuristics (count runs en data_factory, etc.).
## Conventions
- Numeracion 0001+, propia (no comparte con `dev/issues/`).
- Status: `pending | running | done | failed | deferred`.
- Risk: `low` (publico) | `medium` (auth no sensible) | `high` (datos personales).
- Apps listadas en frontmatter — `/flow list --app navegator_dashboard` filtra.
- Acceptance es la fuente de verdad del progreso.
## Output style
Caveman. Tablas markdown. Sin emojis. Sin verbosidad.
Errores: 1 linea con el problema + sugerencia.
## Ejemplos
```
/flow create reddit-sentiment-tracker
# crea dev/flows/0008-reddit-sentiment-tracker.md
# anade fila a INDEX
/flow list --pending
# muestra solo flows no cerrados
/flow status 0001
# acceptance 0/6, todos los checks pendientes
# Tras correr el flow manualmente:
# editas el .md, marcas [x] los checks completados
/flow status 0001
# acceptance 6/6
/flow done 0001 --notes "smoke pass; LLM tardo 14s; recipe robusta"
# mueve a completed/, marca status=done
```
+240
View File
@@ -0,0 +1,240 @@
---
description: "Auto-auditoria: verifica que la sesion registra uso de funciones, detecta gaps (patrones inline repetidos, wrappers saltados, heredocs sin function_id), lanza fn-constructor en paralelo para crear las funciones que faltan, y valida que Claude usara las nuevas en el siguiente turno"
---
# /fn_claude — auto-auditoria + auto-construccion del registry
Comando meta: Claude se audita a si mismo. Verifica que su comportamiento en esta sesion (y las recientes) deja rastro en `call_monitor.operations.db`, detecta gaps reales del registry para el trabajo actual, lanza sub-agentes `fn-constructor` en paralelo para cerrar esos gaps, y verifica que la proxima vez usara las funciones nuevas.
## Objetivos del registry (Norte) — Issues 0086 + 0087
Cada corrida de `/fn_claude` optimiza 4 metricas visibles en Monitor tab del `registry_dashboard`:
1. **MAXIMIZAR `Reg %`** — % de calls con `function_id != ''`. Cada heredoc/bash que reescribe logica baja el ratio. Target: subir cada semana.
2. **MEJORAR uso del registry por Claude** — Claude busca y reusa antes de escribir. `MCP` (mcp/heredoc/fn run) sube, `violations` baja. Si una funcion existe pero Claude no la encuentra, mejorar su `description`/`tags`/`params_schema` (FTS indexa todo).
3. **ACELERAR tareas comunes** — patrones inline repetidos >2x -> `fn-constructor` los convierte en funcion, Claude las usa el siguiente turno. Menos pasos por tarea = mas valor.
4. **PROMOVER COMPOSICIONES A PIPELINES** (issue 0087) — el registry crece **promoviendo secuencias A->B(->C) que se repiten con exito** a pipelines one-shot. Una funcion que hace bien una cosa NO necesita crecer. Pattern detection: `call_monitor sequences --detect --propose` (cron 6h activo) + tab `Promotion candidates` del dashboard.
Si `/fn_claude` no mueve estas 4 metricas, no esta haciendo su trabajo.
## Infraestructura de discovery activa (issue 0087)
Cada turno tienes capacidades ya cargadas SIN buscar. Si no las usas estas pagando el coste de FTS innecesariamente:
| Senal | Donde | Que hacer |
|---|---|---|
| Linea `CAPABILITIES (cache 1h): TOP: ... FRESH (7d): ... PIPELINES: ...` en cada UserPromptSubmit | hook `hook_capabilities_inject.sh` | Antes de buscar con `mcp__registry__fn_search`, mira si la funcion que necesitas esta en TOP/FRESH/PIPELINES. Si si, ve directo a `fn show <id>` (1 read) o `./fn run <id>` (0 reads). |
| `<system-reminder>FUZZY-MATCH (issue 0087): your Bash command may already be a function. USE: ./fn run <id> -> <signature>` aparecido mid-flight | hook `hook_fn_match.sh` (PreToolUse, Bash matcher) | El hook detecto que tu Bash inline coincide con una funcion del registry. **NO ignores el reminder** — abandona el inline, llama a `./fn run <id>` o `mcp__registry__fn_run id="<id>"`. Si crees que la sugerencia es falso positivo, justifica brevemente antes de seguir inline (queda en violations). |
| Hint AUSENTE para una query corta (`rsi sma` < 3 tokens) | threshold `raw_score >= 4.0` no alcanzado | NO interpretar la ausencia de hint como "no existe funcion". Usa `mcp__registry__fn_search` con query mas rica (3+ tokens del dominio). |
| Falso positivo conocido: `agent` token | `robots.txt user-agent` matchea `agent_scaffold` | Ignora el reminder y sigue. Cost = 1 reminder ignorable. |
## Como combinar la 3 senales para minimizar pasos
1. **User prompt llega** -> lees `CAPABILITIES` line. Si la tarea encaja claramente con TOP/FRESH -> usa directo.
2. **Vas a escribir Bash inline** -> el hook PreToolUse lo intercepta. Si dispara FUZZY-MATCH -> usa `./fn run <id>`.
3. **No hay match y necesitas codigo** -> `mcp__registry__fn_search` con 3+ tokens. Si sigue sin hit -> delega a `fn-constructor` (no escribas inline). Patron repetido detectado por `call_monitor sequences` se promovera a pipeline en proximas iteraciones.
## Las 4 metricas norte (donde vigilarlas)
- `Reg %` (Monitor KPI) — % calls con function_id no vacio. Sube cuando el registry se usa.
- `MCP` (Monitor KPI) — count calls con tools registry-aware (mcp*/heredoc*/fn_cli_run). Adopcion de patrones canonicos.
- `Errors` / `Violations` (Monitor KPI) — bajan cuando el bucle cierra.
- `Failed Functions` (Monitor sub-tab) — registry-functions que fallaron: diagnostico de bugs prioritarios.
Issue 0085 fase autocompleta. Reemplaza el flujo manual de "veo un patron, decido si extraer, escribo proposal, espero humano, fn-mejorador genera, fn-orquestador opera". Con `/fn_claude` Claude hace todo eso solo, **autonomamente para si mismo**.
---
## Comportamiento (ejecutalo en este orden)
### 1. AUDIT — ¿estoy siendo registrado?
```bash
ROOT="/home/lucas/fn_registry"
MON="$ROOT/projects/fn_monitoring/apps/call_monitor/operations.db"
# Pre-condiciones
[ -f "$MON" ] || { echo "call_monitor.operations.db NO existe — issue 0085a no aplicado"; exit 1; }
[ "$FN_TELEMETRY" = "1" ] || echo "WARNING: FN_TELEMETRY != 1 — wrappers Python/Bash inactivos"
# Metricas de la sesion actual + ultimas 24h
sqlite3 "$MON" <<SQL
SELECT 'calls_session', COUNT(*) FROM calls WHERE session_id = '${CLAUDE_SESSION_ID:-unknown}'
UNION ALL SELECT 'calls_24h', COUNT(*) FROM calls WHERE ts >= CAST(strftime('%s','now','-1 day') AS INTEGER)
UNION ALL SELECT 'violations_24h', COUNT(*) FROM violations WHERE ts >= CAST(strftime('%s','now','-1 day') AS INTEGER)
UNION ALL SELECT 'tool_used_distribution_24h', NULL;
SELECT tool_used, COUNT(*) FROM calls WHERE ts >= CAST(strftime('%s','now','-1 day') AS INTEGER) GROUP BY tool_used ORDER BY 2 DESC;
SQL
```
Si `calls_session = 0` → algo esta mal (hook PostToolUse no fire o BD no escribible). Reporta y para.
Si `mcp_*` / total < 0.4 → estas usando demasiado heredoc/sqlite directo. Reporta como warning.
### 2. GAP — ¿que funciones faltan?
Dos fuentes:
#### 2a. Patrones repetidos en heredocs/Edit
```sql
-- En call_monitor.operations.db
SELECT tool_used, COUNT(*) AS hits
FROM calls
WHERE function_id = ''
AND ts >= CAST(strftime('%s','now','-7 days') AS INTEGER)
AND tool_used IN ('heredoc_py', 'heredoc_bash', 'sqlite_direct')
GROUP BY tool_used;
```
Si `heredoc_py > 5` sin function_id → Claude esta componiendo logica que probablemente debe ser pipeline. Investigar el ultimo heredoc del transcript: si reescribe algo que ya es funcion del registry → violation candidate. Si no, es candidato a pipeline nuevo.
#### 2b. Trabajo actual de la sesion — gap inferido del contexto
Lee el ultimo prompt del usuario y los ultimos 10 turnos. Lista funciones que:
- Has llamado inline (sed/awk/jq custom, transformaciones de datos, parsing).
- Has reinventado (HTTP client raw, SQLite open con flags, FS walks).
- Has compuesto >2 veces con el mismo shape.
Para cada candidato:
```bash
# Verifica si ya existe algo similar en el registry
mcp__registry__fn_search "<keyword del candidato>"
```
Si NO existe match relevante → candidato a `fn-constructor`.
Si existe pero firma incompleta → candidato a `improve_function` (proposal, NO auto-construccion).
### 3. PROPOSE — lista candidatos
Genera tabla:
```
| Candidato | Razon | Lenguaje | Dominio | Evidencia (snippet) |
|---|---|---|---|---|
| <name> | inline_repeated/wrapper_skip/new | go/py/bash | core/infra/... | <heredoc fragment> |
```
Si lista vacia → "no gaps detected, sesion saludable" + reporta metricas. Para.
### 4. CONSTRUCT — lanza fn-constructor en paralelo
Para cada candidato, dispara un sub-agente `fn-constructor` con prompt autocontenido:
```
Agent(subagent_type="fn-constructor", prompt=...)
```
Prompts en PARALELO en un mismo mensaje (varios Agent calls). Pasar:
- nombre propuesto, lang, domain
- firma esperada (params + return)
- pureza
- descripcion + ejemplo de uso (heredoc real detectado)
- nota: "esta funcion la necesita Claude para auto-uso futuro"
### 5. VALIDATE — ¿la proxima sesion la usara?
Despues de que fn-constructor termine:
```bash
./fn index 2>&1 | tail -2
# Verifica que las nuevas funciones existen
for fn in <lista>; do
mcp__registry__fn_show "$fn" >/dev/null && echo "OK: $fn" || echo "FAIL: $fn"
done
```
Tambien actualiza `call_monitor.copied_code` + `function_stats` corriendo:
```bash
cd "$ROOT/projects/fn_monitoring/apps/call_monitor" && ./call_monitor copied-code && ./call_monitor propose
```
### 5b. MEMORIZE — anadir cada funcion nueva a MEMORY.md (issue 0087 pieza 6)
Por cada funcion creada con exito, llama:
```bash
bash "$ROOT/.claude/scripts/append_fn_to_memory.sh" "<fn_id>" "<one-line purpose>"
```
El script es idempotente (si la fn ya esta linkeada, no duplica). Crea `reference_fn_<id>.md` con metadata `type: reference` e indexa la entrada en `MEMORY.md` como linea `- [fn-<id>](reference_fn_<id>.md) — <purpose>`. Asi proximas sesiones cargan MEMORY.md y ven el catalogo de funciones recien creadas sin segunda lookup.
`purpose` = 1 frase derivada del `description` del .md de la funcion (max 80 chars). Si description es larga, recorta. Ejemplo:
- fn_id: `parse_http_log_go_infra`
- purpose: "parsea log Apache/Nginx a struct; pure"
Reporta:
- N funciones nuevas creadas (con IDs)
- N proposals nuevas en `registry.db.proposals`
- Recomendacion al usuario: "proximo turno mencionar/usar `<fn_id>` para validar que el wrapper se invoca correctamente"
### 6. SELF-TEST — telemetria del propio /fn_claude
`/fn_claude` mismo debe quedar registrado. Tras ejecutar, query final:
```bash
sqlite3 "$MON" "SELECT COUNT(*) FROM calls WHERE session_id = '${CLAUDE_SESSION_ID:-unknown}' AND ts >= <inicio_comando>"
```
Si la cuenta no aumento → el comando esta operando fuera de la telemetria (bug). Reportar.
---
## Reglas duras
1. **NO ejecutar fn-constructor para algo que ya existe.** Buscar primero via `mcp__registry__fn_search`. Si match relevante → NO crear duplicado.
2. **NO crear funciones especulativas.** Cada candidato debe tener evidencia real (snippet de heredoc o llamada inline detectada en esta sesion o en `call_monitor.calls` reciente).
3. **PARALELO**: si hay >1 candidato, lanza todos los `fn-constructor` en un solo mensaje con multiples `Agent` calls. NO secuencial.
4. **No autonomous merge**: las funciones nuevas viven en el branch local. NO push automatico. Humano revisa y push manual.
5. **Limites duros**: max 5 funciones nuevas por invocacion. Si detectas mas, prioriza por evidence weight (`occurrences * recency`) y reporta el resto como pending.
6. **Si la sesion no esta siendo registrada (`calls_session = 0`)**: ABORT antes de fase 2. No tiene sentido auto-construir sin telemetria.
---
## Output canonico
```
=== /fn_claude — auto-auditoria ===
session_id: <id>
calls_session: N
calls_24h: M (mcp_ratio: 0.XX)
violations_24h: K
pending_proposals: P (existentes en registry.db)
GAPS DETECTADOS:
1. <name>_<lang>_<domain> — razon — evidencia
2. ...
LANZADOS (en paralelo):
fn-constructor #1: <name1> → en progreso
fn-constructor #2: <name2> → en progreso
...
VALIDADAS tras ./fn index:
✓ <name1>_<lang>_<domain>
✓ <name2>_<lang>_<domain>
PROPOSALS NUEVAS: <count>
PROXIMO TURNO: menciona `<name1>` para validar wrapper.
```
---
## Cuando usar
- Al inicio de una sesion larga, para verificar telemetria activa.
- A media sesion, cuando notes que estas reescribiendo el mismo bloque.
- Antes de cerrar sesion, para capitalizar lo aprendido como funciones reutilizables.
- Tras `/autonomous-task` para validar que el orquestador no genero ruido (proposals/funciones huerfanas).
---
## Cuando NO usar
- En sesiones cortas (<5 turnos) — no hay datos suficientes.
- Si `call_monitor.operations.db` no esta inicializado (`call_monitor init` primero).
- Si el usuario quiere control manual del proceso de extraccion. Este comando es agresivo.
+93
View File
@@ -0,0 +1,93 @@
---
description: "Gestiona issues del registry en dev/issues/. Subcomandos: list, show, status, board, dep, roadmap, tag, done, stale, create. Frontmatter YAML canonico (issue 0100)."
---
# /issue — Gestionar issues del registry
Issues viven en `dev/issues/NNNN-<slug>.md` con frontmatter YAML canonico (id, title, status, type, domain, scope, priority, depends, blocks, related, created, updated, tags).
Allowlists en `dev/TAXONOMY.md` (no inventar valores).
Diferencia con `dev/flows/`:
- **Issues** = bugs, features, refactors, chores, epics de implementacion.
- **Flows** = casos de uso end-to-end multi-app.
## Sintaxis
```
/issue list [--domain X] [--type Y] [--status Z] [--prio P] [--epic NNNN]
/issue show NNNN
/issue status NNNN # acceptance % + estado deps
/issue board # kanban pendiente/in-progress/bloqueado/done
/issue dep NNNN # arbol bloquea/depende
/issue roadmap NNNN # epic + sub-IDs (NNNNa, NNNNb, ...)
/issue tag NNNN +X -Y # mantenimiento tags/domain
/issue done NNNN # mueve a completed/, valida deps
/issue stale [--days 30]
/issue create <slug> --type T --domain D [--prio P] [--depends NNNN]
```
## Implementacion
**Fase 1 (manual via Claude):**
El agente lee `dev/issues/*.md`, parsea frontmatter YAML con `yaml.safe_load`, aplica el filtro, imprime tabla.
```python
import yaml, pathlib, re
issues = []
for f in pathlib.Path("dev/issues").glob("*.md"):
if f.name in {"README.md", "template.md"}: continue
txt = f.read_text()
m = re.match(r"^---\n(.*?)\n---", txt, re.S)
if not m: continue
fm = yaml.safe_load(m.group(1)) or {}
fm["_path"] = str(f)
issues.append(fm)
# filter + print
```
**Fase 2 (cuando 0101 dev_console exista):**
Cada subcomando se mapea a `./apps/dev_console/dev_console issue <subcomando> $ARGS`.
## Subcomandos clave
### `list`
Imprime tabla `id | title | status | type | domain | priority | depends_pending`. Filtrable por flags.
### `show NNNN`
Read directo del .md + render del frontmatter como tabla + body como markdown.
### `status NNNN`
Cuenta checkboxes en `## Acceptance` + chequea si todos los `depends` estan en `status: completado`. Si alguno no, marca `bloqueado`.
### `board`
Tabla 4 columnas (pendiente / in-progress / bloqueado / completado_hoy). Card por issue: id + title + prio. Status `bloqueado` se calcula on-the-fly desde `depends`.
### `roadmap NNNN`
Si `type: epic`: lista sub-issues `NNNNa`, `NNNNb`, etc. con su estado. Si no epic: error "not an epic".
### `done NNNN`
1. Lee frontmatter.
2. Verifica todos `depends` cerrados (sino, error).
3. Cuenta `## Acceptance` 100% (sino, error).
4. `git mv dev/issues/NNNN-*.md dev/issues/completed/`.
5. Actualiza `status: completado` + `updated: today`.
### `create <slug> --type T --domain D`
Genera siguiente ID libre (max existing + 1, zero-padded 4). Scaffold desde plantilla minima con frontmatter rellenado.
## Reglas
- Domain debe estar en `dev/TAXONOMY.md` allowlist.
- Scope/type/priority idem.
- `id` siempre string `"NNNN"` (zero-padded, sub-IDs con sufijo `a-z`).
- Modificar frontmatter SIEMPRE preserva campos no tocados (no overwrite).
+171
View File
@@ -109,6 +109,177 @@ metabase_update_dashboard(client, dash["id"], dashcards=[
**Filtros de list_dashboards:** `all`, `mine`, `archived`
### Dashboards — helpers compositivos (añadir KPIs a dashboard existente)
Helpers para el flujo tipico "anadir N cards (KPI) al final de un tab existente reusando los mismos filtros que otro card vecino". Evitan los gotchas: replicar `parameter_mappings`, calcular `row` libre, escapado raro de `column_settings`, generacion de `lib/uuid` en MBQL.
```python
from metabase import (
metabase_mbql_from_source_card,
metabase_copy_dashcard_mappings,
metabase_dashboard_next_row,
metabase_dashboard_append_row,
metabase_viz_column_format,
metabase_smartscalar_anothercolumn_viz,
)
```
#### `metabase_mbql_from_source_card`
Construye `dataset_query` MBQL sobre una saved-card (`source-card`), con aggregations + joins + filters + breakouts + segunda stage de expressions. Genera `lib/uuid` automatico en cada nodo.
```python
dq = metabase_mbql_from_source_card(
database_id=6,
source_card_id=5305,
aggregations=[
{"op": "sum", "field": "PrecioVenta", "base_type": "type/Decimal"},
{"op": "sum", "field": "PrecioCompra", "base_type": "type/Decimal"},
{"op": "sum", "field": "PrecioTasas", "base_type": "type/Float"},
],
joins=[
{"alias": "Centros - idCentro", "source_card_id": 4076,
"fields": "none", "local_field": "idCentro", "local_base_type": "type/Text",
"foreign_field_id": 17316, "foreign_base_type": "type/Text"},
],
filters=[["not-empty", {}, ["field", {"base-type": "type/Text"},
"Centros - idCentro__Companies__name"]]],
expressions=[
{"name": "MasadeMargen", "expr":
{"op": "-", "args": [{"field": "sum"},
{"op": "+", "args": [{"field": "sum_2"}, {"field": "sum_3", "base_type": "type/Float"}]}]}},
{"name": "Margen", "expr":
{"op": "coalesce", "args": [
{"op": "/", "args": [
{"op": "-", "args": [{"field": "sum"},
{"op": "+", "args": [{"field": "sum_2"}, {"field": "sum_3", "base_type": "type/Float"}]}]},
{"field": "sum"}]},
0]}},
],
)
```
Ops soportadas en expressions: `+`, `-`, `*`, `/`, `coalesce`, `case`. Referencia a otra expresion en la misma stage: `{"ref": "Margen"}`. Aliases de aggregations son posicionales: `sum`, `sum_2`, `sum_3`... (orden = declaracion).
#### `metabase_copy_dashcard_mappings`
Copia los `parameter_mappings` de un dashcard "donante" a un card nuevo. Devuelve lista lista para pegar en `dashcards_add`.
```python
mappings = metabase_copy_dashcard_mappings(
client,
dashboard_id=734,
source_card_id=9918, # card donante con 18 filtros mapeados
dest_card_id=9947, # card destino nueva
)
# Devuelve [{"parameter_id","card_id","target"}, ...] con card_id=9947
```
#### `metabase_dashboard_next_row`
Calcula el primer `row` libre al final de un tab.
```python
row = metabase_dashboard_next_row(client, dashboard_id=734, tab_id=191)
# row=12 si el ultimo card termina en row+size_y=12
# tab_id=0 → dashboards sin tabs
```
#### `metabase_dashboard_append_row`
Combo: append N cards en una fila horizontal al final del tab, copiando mappings de un donante. Una sola llamada hace `next_row` + grid math + `copy_mappings` + `update_dashboard_safe`.
```python
metabase_dashboard_append_row(
client,
dashboard_id=734,
tab_id=191,
card_ids=[9947, 9948, 9949],
height=4,
donor_card_id=9918, # mismos 18 filtros del dashboard
grid_width=24, # default Metabase v0.59
)
# Coloca 3 cards de size_x=8 en row=next, cols 0/8/16, con mappings copiados
```
#### `metabase_viz_column_format`
Construye una entrada de `column_settings` con la clave JSON-escaped (`'["name","Margen"]'`) sin tener que recordar el formato exacto.
```python
metabase_viz_column_format("Margen", number_style="percent", decimals=2)
# {'["name","Margen"]': {"number_style": "percent", "decimals": 2}}
metabase_viz_column_format("MasadeMargen", number_style="currency",
currency="EUR", decimals=0, currency_in_header=False)
# {'["name","MasadeMargen"]': {...}}
```
Mergea varios resultados en `column_settings` de las visualization_settings.
#### `metabase_smartscalar_anothercolumn_viz`
Construye `visualization_settings` completo para `display=smartscalar` con comparativa tipo `anotherColumn` (compara dos columnas de la misma fila — no requiere breakout temporal).
```python
viz = metabase_smartscalar_anothercolumn_viz(
main_column="Margen",
compare_column="Margen_N1",
label="vs N-1",
number_style="percent",
decimals=2,
)
# Setear en /api/card via PUT visualization_settings=viz
```
**⚠ Gotcha smartscalar Metabase v0.59:** el visualization solo acepta `type: "anotherColumn"` cuando la query NO produce filas multiples. Si Metabase muestra el error *"Agrupa solo por un campo de tiempo para ver como ha cambiado con el tiempo"*, hace falta un **breakout temporal** en la MBQL (ej. `breakouts=[{"field":"fecha","base_type":"type/Date","temporal_unit":"month"}]`) y usar el comparison `previousValue` en lugar de `anotherColumn`. Alternativa: `metabase_smartscalar_kpi_sql` + `metabase_smartscalar_kpi_payload` (patron 2-row nativo) si la card es SQL nativo.
#### Patron canonico — anadir 3 KPI cards a tab existente
```python
import os, sys
sys.path.insert(0, "python/functions")
from metabase import (
MetabaseClient, metabase_create_card, metabase_mbql_from_source_card,
metabase_dashboard_append_row, metabase_viz_column_format,
metabase_smartscalar_anothercolumn_viz,
)
c = MetabaseClient("https://reports.autingo.es", os.environ["MB_API_KEY"])
# 1) MBQL reusando una saved-card como source
def query():
return metabase_mbql_from_source_card(
database_id=6, source_card_id=5305,
aggregations=[
{"op":"sum","field":"PrecioVenta","base_type":"type/Decimal"},
{"op":"sum","field":"PrecioCompra","base_type":"type/Decimal"},
{"op":"sum","field":"PrecioTasas","base_type":"type/Float"},
],
# joins/filters/expressions ...
)
# 2) Crear cards
card1 = metabase_create_card(c, "Masa de Margen", query(),
display="scalar", collection_id=500)
viz1 = {"scalar.field": "MasadeMargen",
"column_settings": metabase_viz_column_format(
"MasadeMargen", number_style="currency", currency="EUR", decimals=0)}
c._http.request("PUT", f"/api/card/{card1['id']}", json={"visualization_settings": viz1})
card2 = metabase_create_card(c, "Margen", query(), display="smartscalar", collection_id=500)
viz2 = metabase_smartscalar_anothercolumn_viz(
main_column="Margen", compare_column="Margen_N1", number_style="percent", decimals=2)
c._http.request("PUT", f"/api/card/{card2['id']}", json={"visualization_settings": viz2})
# 3) Append fila al tab con mappings copiados del donante
metabase_dashboard_append_row(
c, dashboard_id=734, tab_id=191,
card_ids=[card1["id"], card2["id"]],
height=4, donor_card_id=9918,
)
```
### Documents (ProseMirror)
Los "documents" son páginas narrativas editables con texto rico y cards embebidas. **No hay helpers en fn_registry todavía** — usa el endpoint REST directamente a través de `client._http`.
+53
View File
@@ -0,0 +1,53 @@
# /new-cpp-app — Crear app C++ nueva con scaffolder estandar
Wrapper sobre el pipeline `init_cpp_app_bash_pipelines`. Genera la estructura canonica que cumple `cpp/PATTERNS.md` y `.claude/rules/cpp_apps.md` (main.cpp con `cfg.about/log/panels`, sin `app_menubar` manual, dockspace via framework), registra la app en `cpp/CMakeLists.txt`, crea repo Gitea `dataforge/<name>` y ejecuta `fn index`.
```bash
cd /home/lucas/fn_registry
./fn run init_cpp_app $ARGUMENTS
```
## Uso
```
/new-cpp-app <name> [--project <p>] [--domain <d>] [--desc "..."] [--tags "a,b"]
```
## Ejemplos
```bash
# App suelta en cpp/apps/<name>/
/new-cpp-app my_tool --desc "Herramienta para X"
# App dentro de un proyecto
/new-cpp-app finance_panel --project budget --desc "Panel de finanzas" --tags "finance,dashboard"
```
## Que genera
```
<dir>/
main.cpp # Plantilla canonica: panels[] + cfg.about + cfg.log + run_app(cfg, render)
CMakeLists.txt # add_imgui_app(<name> main.cpp)
app.md # Frontmatter completo (lang:cpp, framework:imgui, dir_path, repo_url)
```
Mas registro en `cpp/CMakeLists.txt`, repo Gitea con commit inicial, y `fn index` para que aparezca en `registry.db`.
## Despues de crear
1. Editar `app.md` y completar `uses_functions` cuando la app consuma funciones del registry.
2. Anadir las funciones al `CMakeLists.txt` como paths absolutos: `${CMAKE_SOURCE_DIR}/functions/<dom>/<func>.cpp`.
3. Build: `/compile <name>` o `cd cpp && cmake --build build --target <name> -j`.
## Cuando NO usar
NUNCA — esta es la unica via para crear apps C++ nuevas. Si el scaffolder no cubre un caso, modificar la plantilla en `bash/functions/pipelines/init_cpp_app.sh`. Escribir `main.cpp + CMakeLists.txt + app.md` a mano esta prohibido por `.claude/rules/cpp_apps.md`.
## Auditoria post-creacion
```
fn doctor cpp-apps
```
Lista apps que se desvian del estandar (sin `cfg.about`, con `app_menubar` manual, dockspace duplicado, etc.).
+97
View File
@@ -0,0 +1,97 @@
---
description: "Recordatorio operativo para usar subagentes fn (constructor/executor/recopilador/analizador/mejorador) y paralelizar trabajo independiente"
---
# /subagentes — usa subagentes fn y paraleliza
Recuerda: antes de escribir codigo nuevo o ejecutar pipelines en serie, **delega a subagentes** y **paraleliza** llamadas independientes (un mensaje, varios `Agent` calls).
---
## Mapa de subagentes fn (ciclo reactivo)
| Fase | Agente | Cuando dispararlo |
|---|---|---|
| 1 CONSTRUIR | `fn-constructor` | Falta funcion/tipo/test reutilizable. NUNCA escribir inline en `apps/` si es reutilizable |
| 2 EJECUTAR | `fn-executor` | Correr pipeline/funcion del registry + registrar ejecucion en `operations.db` |
| 3 RECOPILAR | `fn-recopilador` | Auditar integridad de `operations.db`. Modo `design-e2e <app>` propone bloque `e2e_checks` |
| 4 ANALIZAR | `fn-analizador` | Ejecutar `e2e_checks` de `app.md`, veredicto pass/fail, persistir en `e2e_runs` |
| 5 MEJORAR | `fn-mejorador` | Convertir fallos de `e2e_runs` en `proposals` con evidencia trazable |
| 6 META | `fn-orquestador` | Recorrer fases 1-5 solo hasta convergencia. Sandbox `auto/<issue>`. Issue 0069 |
**Pre-condiciones de `fn-orquestador`** (abortara si no se cumplen):
- Migration `fn_operations/migrations/006_task_runs.sql` aplicada
- Issue con criterios de aceptacion **verificables programaticamente** (no "funciona bien")
- `master` local up-to-date con `origin/master`
- Branch `auto/<issue>` NO existe ya (limpiar previo si hace falta)
- `gh` autenticado (PR draft al converger)
- Tipo soportado: `feature_app_simple`, `bugfix_with_repro`, `refactor_safe`, `add_e2e_check`
**Aislamiento por worktree**: cada run crea `/tmp/fn_orq_<issue>_<ts>/` via `git worktree add`. Working tree principal del usuario queda intacto. N orquestadores paralelos = N worktrees independientes. `task_runs` persiste en BD del repo principal (auditoria sobrevive aunque borres worktree).
## Otros subagentes utiles
- `Explore` — busquedas amplias en codebase (>3 queries) sin contaminar contexto principal
- `general-purpose` — research multi-step open-ended
## Reglas duras
1. **Paralelo real**: tareas independientes → un mensaje con varios `Agent` calls. NO en serie.
2. **Briefing autocontenido**: subagente no ve historial. Pasar paths absolutos, IDs, criterio exito.
3. **No delegar comprension**: nada de "haz lo que veas". Especificar que cambiar, donde, por que.
4. **Verificar output**: leer diff/resultado, no confiar en resumen del subagente.
5. **No duplicar**: si delegas research, no lo repitas tu.
## Patrones canonicos de paralelismo
- 3 funciones de registry independientes → 3 `fn-constructor` en paralelo
- Auditar N apps → N `fn-recopilador` en paralelo
- Validar varias apps → N `fn-analizador` en paralelo
- Build cpp + tests py + audit operations.db → 3 calls paralelos
- Tras `fn-analizador` con fallos → `fn-mejorador` por cada `run_id`
- Tarea multi-fase autonoma (issue con criterios verificables) → `fn-orquestador` (1 sola run, NO recursivo)
## Anti-patrones
- Escribir funcion reutilizable inline en `apps/` (debe ir a `functions/` via `fn-constructor`)
- Lanzar subagentes en serie cuando son independientes
- Prompt de 1 linea sin contexto ("arregla esto")
- Invocar subagente y luego hacer tu mismo el trabajo
- Spawn `fn-orquestador` sin migration 006 o sin issue verificable (abortara)
- `fn-orquestador` recursivo (un orquestador no spawn-ea otro)
## Checklist pre-respuesta
- ¿>1 tarea independiente? → paralelizar
- ¿Hace falta funcion/tipo nuevo? → `fn-constructor`, NO inline
- ¿Hay que ejecutar/auditar/validar? → fase 2/3/4 segun toque
- ¿`e2e_runs` con fallos? → `fn-mejorador`
- ¿Issue con criterios verificables + tipo soportado? → `fn-orquestador` (chequear pre-condiciones)
- ¿Research amplio (>3 queries)? → `Explore`
## Plantilla minima de prompt para subagente
```
Contexto: <que repo, que app, que objetivo>
Input: <paths absolutos, IDs registry, run_id si aplica>
Tarea: <accion concreta y acotada>
Criterio exito: <como sabe que termino>
Limites: <que NO debe tocar>
Telemetria: tus tool calls quedan registradas en projects/fn_monitoring/apps/call_monitor/operations.db
via hook PostToolUse heredado de settings.local.json. Sigue patrones canonicos
(mcp__registry__fn_*, ./fn run, heredoc importando) — los antipatrones se loguean
como violations.
```
## Telemetria heredada (issue 0085 hardening 5)
Los hooks de `.claude/settings.local.json` se heredan automaticamente por cada sub-agente que Claude Code lance via la tool `Agent`. Eso significa:
- Cada Bash, Edit, Write, MultiEdit, `mcp__registry__*` del sub-agente dispara `hook_call_monitor.sh` exactamente igual que en la sesion principal.
- El `session_id` del JSON de input del hook viene del sub-agente, distinto al de la sesion padre. Util para auditar comportamiento por agente.
- Las violations detectadas (sqlite3 directo, heredoc reinventando, etc) cuentan tambien para sub-agentes — un `fn-constructor` que reescribe inline en lugar de delegar a otro `fn-constructor` queda registrado.
- `FN_TELEMETRY=1` esta en el `env` block de settings.local.json — los heredocs Python/Bash de sub-agentes ya tienen wrappers activos automaticamente.
Implicacion: NO necesitas pasar flags `--telemetry` a sub-agentes. Solo asegurate de que el prompt sigue patrones canonicos. La regla `.claude/rules/registry_calls.md` se aplica igual.
Si un sub-agente abre un proceso hijo que escapa al hook (ej. `nohup ... &`, daemons), ese subproceso queda fuera de la telemetria — documentalo en el prompt si es un caso valido.
+170
View File
@@ -0,0 +1,170 @@
---
name: version
description: Bumpear semver de un modulo, framework, paquete o app del registry. Edita <target>.md::version + ## Capability growth log. NO commitea.
---
# /version
Bumpea la version de un **modulo, framework, paquete o app** del registry siguiendo SemVer estricto y mantiene el `## Capability growth log` sincronizado con `<target>.md::version`.
Disenado para usarse desde `/fix-issue` cuando el cambio afecte:
- `modules/<X>/` (cualquier modulo C++) — edita `module.md`
- `cpp/framework/` — edita `modules/framework/module.md`
- `apps/<X>/` o `projects/<P>/apps/<X>/` — edita `app.md`
- Otros paquetes versionados con `<target>.md` y campo `version:`
## Inputs
```
/version <path> <major|minor|patch> "<reason>"
```
- `<path>`: directorio del target (ej. `modules/data_table`, `cpp/framework`, `apps/chart_demo`, `projects/fn_monitoring/apps/registry_dashboard`).
- `<major|minor|patch>`: tipo de bump SemVer.
- `<reason>`: 1-frase humana — lo que cambia. Se inserta en el log.
## Resolucion del archivo target
| Path empieza por | Archivo a editar |
|---|---|
| `modules/` | `<path>/module.md` |
| `cpp/framework` | `modules/framework/module.md` |
| `apps/` | `<path>/app.md` |
| `projects/*/apps/` | `<path>/app.md` |
| `projects/*/analysis/` | `<path>/analysis.md` |
Si no encuentra archivo target -> ERROR.
## Reglas SemVer
### Modulos / framework
| Bump | Cuando |
|---|---|
| `major` | Cambios breaking en API publica: firma de entry function, layout de State struct expuesto, eliminacion de members, cambio incompatible de comportamiento. |
| `minor` | Adiciones backwards-compatible: nuevo evento opt-in, nuevo renderer, nuevo helper, nuevo miembro. |
| `patch` | Bugfix sin cambio de API. |
Refactor interno SIN cambio de API publica -> `minor` (no major).
### Apps
| Bump | Cuando |
|---|---|
| `major` | Breaking observable por usuarios: CLI args incompatibles, schema BBDD propia rompe lectores viejos, formato wire (HTTP/gRPC) incompatible, eliminacion de panel/feature que la gente usaba. |
| `minor` | Feature aditiva: nuevo panel, nuevo endpoint, nueva opcion CLI, nueva tab, mejora visible no rompedora. |
| `patch` | Bugfix sin cambio observable. Refactor interno. Mejoras de perf. |
Bump de **dependencia** (modulo/funcion del registry) que mejora la app pero la app no cambia su API -> `patch` (la app no es responsable de la mejora; el modulo si).
## Flujo
### 1. Validar input
- `<target_file>` existe -> si no, ERROR.
- Bump type en {major, minor, patch} -> si no, ERROR.
- Reason no vacia -> si no, ERROR.
### 2. Leer version actual
Parsear frontmatter. Buscar `version: X.Y.Z`. Si no existe:
- Para `module.md` -> ERROR "module.md sin campo version".
- Para `app.md` -> asumir `0.1.0` (baseline) e insertar el campo despues de `domain:`.
### 3. Calcular proxima version
```
1.4.0 + major = 2.0.0
1.4.0 + minor = 1.5.0
1.4.0 + patch = 1.4.1
```
Major bump -> minor y patch a 0. Minor bump -> patch a 0.
### 4. Editar `<target_file>`
Cambiar linea `version: <old>` por `version: <new>`.
### 5. Anadir entrada a `## Capability growth log`
Insertar al inicio de la lista (lineas posteriores al header `## Capability growth log`):
```markdown
- v<new> (<fecha YYYY-MM-DD>) — <reason>
```
Si la seccion no existe -> crearla al final del archivo antes de `## Notes` (o al final si no hay Notes).
### 6. Verificar drift de members (solo modulos, opcional)
Si la herramienta `fn doctor modules` existe (post 0107a) y el target es modulo:
- Compara `members:` actual vs ultima version registrada en `registry.db::modules_history`.
- Si hay diff en members y bump es `patch` -> WARNING.
- Si hay diff en API publica y bump no es `major` -> ERROR (require `--force`).
No aplica a apps (no tienen `members:`).
### 7. Stage en git
`git add <target_file>`. NO commit. El commit final lo hace el flujo padre.
### 8. Reportar
```
/version apps/chart_demo minor "anade tab radar chart"
apps/chart_demo/app.md
version: 1.2.0 -> 1.3.0
## Capability growth log: + v1.3.0 (2026-05-18) — anade tab radar chart
Staged. NO committed.
Next: terminar el fix-issue y hacer commit con el resto de cambios.
```
## Reglas criticas
- **NUNCA commit**. `/version` solo edita + stage. El commit lo hace el flujo padre (`/fix-issue`, `/git-push`).
- **NUNCA saltar version**. No 1.4.0 -> 1.4.2 directo.
- **NUNCA bajar version**. Si rollback, crea nueva version superior con comportamiento viejo restaurado.
- **fecha = HOY** (`date +%Y-%m-%d`).
- **reason** comprensible sin contexto del PR actual.
## Referenciado desde
- `/fix-issue` — al detectar cambios en `modules/`, `cpp/framework/`, `apps/<X>/` o `projects/*/apps/<X>/`, sugiere ejecutar `/version` antes del commit final.
- `.claude/rules/cpp_apps.md` — politica de bump.
- `dev/issues/0107-modules-standardization.md` — origen del flujo (modulos).
## Ejemplos
```
# Bug fix en data_table (modulo)
/version modules/data_table patch "fix off-by-one en seleccion multi-row con shift+click"
# -> 1.4.0 -> 1.4.1
# Feature opt-in en framework
/version cpp/framework minor "anade cfg.auto_dockspace para overlay de paneles flotantes"
# -> 1.1.0 -> 1.2.0
# Feature en app C++
/version apps/chart_demo minor "anade tab radar chart con datos sinteticos"
# -> 1.2.0 -> 1.3.0
# Bug fix en app de proyecto
/version projects/fn_monitoring/apps/registry_dashboard patch "fix tooltip que mostraba duration_ms en segundos"
# -> 0.4.1 -> 0.4.2
# Breaking en app: cambia schema de su BBDD propia
/version apps/kanban major "cards.assignee_id pasa a ser TEXT[] (era TEXT); requiere migracion 008"
# -> 1.0.0 -> 2.0.0
```
## Anti-patrones
| Anti-patron | Por que es malo |
|---|---|
| Editar `version:` a mano sin `## Capability growth log` | Drift entre version y log; nadie sabe que cambio. |
| Bumpear major en app por refactor interno | Confunde al usuario; refactor es patch. |
| Patch para feature visible | Usuario no se entera que esta disponible. |
| Reason "cambios varios" / "mejoras" | Inutil para auditar. Una frase concreta. |
| Bump de app sin tocar codigo de la app (solo dep) | Bump va al modulo, no a la app. |
+67
View File
@@ -0,0 +1,67 @@
---
description: "Vista cross-cutting de issues + flows. Subcomandos: today, weekly, search, dashboard. Mezcla los dos universos en una lista priorizable."
---
# /work — Vista cross-cutting issues + flows
Issues = trabajo de implementacion. Flows = casos de uso multi-app. `/work` los muestra juntos para responder "que hago ahora" sin saltar entre dos sitios.
## Sintaxis
```
/work today # top items prio alta + deps satisfechas (issues + flows)
/work weekly # review semanal: closed vs planeados
/work search "texto" # FTS sobre issues + flows + completed
/work dashboard # JSON consumible por tab Work (issue 0102)
```
## Implementacion
**Fase 1 (manual via Claude):**
El agente lee `dev/issues/*.md` + `dev/flows/*.md`, parsea frontmatter YAML, ordena por:
1. `priority: alta` primero.
2. `status: pendiente` con `depends` todos `completado` (no bloqueados).
3. Items con DoD/Acceptance >=80% (a punto de cerrar).
4. Fecha `updated` mas reciente.
Imprime tabla unificada:
```
KIND | ID | TITLE | PRIO | STATUS | NEXT STEP
issue| 0099 | datahub app launcher | alta | pendiente | revisar deps
flow | 0001 | hn-top-stories | high | pending | cerrar DoD user-facing
issue| 0100 | migrate issue frontmatter | alta | pendiente | ejecutar pipeline
...
```
**Fase 2 (cuando 0101 dev_console exista):**
`./apps/dev_console/dev_console work <subcomando> $ARGS`.
## Subcomandos
### `today`
Filtro: `priority in (alta, media)` + `status: pendiente` + dependencias resueltas. Max 10 items. Si hay >10, prioriza `alta` y avisa "N items pendientes en cola".
### `weekly`
Git log `--since='1 week ago'` sobre `dev/issues/completed/` y `dev/flows/completed/` -> tabla de items cerrados. Comparado con `created: <esta semana>` -> ratio in/out.
### `search "texto"`
`grep -ri` sobre `dev/issues/` + `dev/flows/` (incluido completed/), filtra por title/body. Output: `path:line: match`.
### `dashboard`
Output JSON estructurado para consumo por tab Work del `registry_dashboard` (issue 0102). Estructura:
```json
{
"issues": {"pendiente": [...], "in-progress": [...], "bloqueado": [...], "completado_24h": [...]},
"flows": [{"id": "0001", "dod_percent": 50, "user_facing_percent": 0, "...": ...}],
"telemetry": {"calls_24h": N, "violations_24h": N, "pending_proposals": N}
}
```
+8
View File
@@ -21,6 +21,7 @@ Reglas operativas del proyecto. Cada archivo es una regla independiente.
| 15 | [projects.md](projects.md) | Projects: agrupar apps, analysis y vaults bajo un tema |
| 16 | [kiss.md](kiss.md) | KISS en proyectos y apps: cuestionar herramientas externas, sin abstracciones especulativas |
| 17 | [apps_tbd.md](apps_tbd.md) | Trunk-based development obligatorio en apps generadas con `fn` (registry exento) |
| 17b | [apps_subrepo.md](apps_subrepo.md) | Apps son sub-repos Gitea (apps/* gitignored). `git init` dentro de cada app nueva ANTES de limpiar worktree, sino se pierde el codigo |
| 18 | [uses_functions.md](uses_functions.md) | Convencion de uses_functions para C++: el .md del consumidor declara las dependencias |
| 19 | [cpp_apps.md](cpp_apps.md) | Estandarizacion de apps C++: estructura, CMake, app.md, sub-repo, runtime — apunta a cpp/PATTERNS.md y cpp/DESIGN_SYSTEM.md como autoritativas |
| 20 | [artefactos.md](artefactos.md) | Termino paraguas para apps, analysis, vaults, projects y playgrounds (todo lo que no es codigo reutilizable) |
@@ -30,3 +31,10 @@ Reglas operativas del proyecto. Cada archivo es una regla independiente.
| 24 | [feature_flags.md](feature_flags.md) | TBD: feature flags para mergear codigo incompleto sin romper master. Patrones por stack (Go/TS/Bash/Py), branch-by-abstraction, anti-patrones |
| 25 | [db_migrations.md](db_migrations.md) | Migraciones SQLite obligatorias para cualquier cambio de schema. Aditivas, idempotentes, archivos numerados. Nunca borrar .db ni modificar migraciones existentes |
| 26 | [e2e_validation.md](e2e_validation.md) | Contrato `e2e_checks` en `app.md` consumido por fn-analizador (fase 4 del bucle reactivo). Issue 0068 |
| 27 | [registry_calls.md](registry_calls.md) | Patrones canonicos para invocar funciones del registry (MCP inspect / MCP run / heredoc compose), antipatrones, excepciones, telemetria. Issue 0085 |
| 28 | [delegation.md](delegation.md) | Si vas a escribir logica reutilizable inline -> spawn fn-constructor inmediato + tag de grupo + usar en mismo turno. Issue 0086 |
| 29 | [capability_groups.md](capability_groups.md) | Tags planos + paginas madre `docs/capabilities/<grupo>.md` para desbloquear clusters de funciones en un read. Issue 0086 |
| 30 | [function_growth_and_self_docs.md](function_growth_and_self_docs.md) | Contrato self-doc de cada `.md` (Ejemplo + Cuando usarla + Gotchas + Growth log) + crecimiento del registry por **promocion de composiciones** a pipelines, NO por inflado de funciones. Issue 0087 |
| 31 | [autonomous_loop.md](autonomous_loop.md) | Reglas para `fn-orquestador` + `/autonomous-task`: sandbox obligatorio, paths protegidos, filtro proposals auto-aplicables, watchdog, idempotencia. Issue 0069 |
| 32 | [../../dev/TAXONOMY.md](../../dev/TAXONOMY.md) | Allowlist canonica para dominios/tipos/scopes/estados/prioridades + flow patterns. Aplica a `dev/issues/` y `dev/flows/`. Issues 0100 + 0103 |
| 33 | [project_commands.md](project_commands.md) | Slash commands por project (`.claude/commands/<project>/`) expuestos via symlink. Desde fn_registry: `/<project>:foo`. Desde el project: `/foo`. Sin colision. |
+74
View File
@@ -0,0 +1,74 @@
## Apps son sub-repos Gitea independientes — gotcha al usar worktrees
**Regla operativa critica** descubierta el 2026-05-18 durante implementacion del flow 0008.
### El gotcha
`apps/*/` esta en `.gitignore` del repo `fn_registry`. Cada app es **su propio repo Gitea** en `dataforge/<app_name>` con su `.git/` dentro de `apps/<app_name>/`. Esto significa:
- Cuando un agente trabaja en un git **worktree** del repo padre y crea `apps/<nueva_app>/`, los archivos viven SOLO en el working directory del worktree.
- Como `apps/*/` esta gitignored en el repo padre, los archivos **no se pueden commitear** al worktree del repo padre.
- Cuando se hace `git worktree remove --force worktrees/<slug>/`, el working directory entero se borra — **el codigo de la app desaparece**.
**Consecuencia**: una app creada dentro de un worktree del repo padre se pierde al limpiar el worktree salvo que se haya promovido a su propio sub-repo Gitea ANTES.
### El patron correcto al crear apps en worktrees
```bash
# 1. Agente trabaja en worktree del repo padre
cd /home/lucas/fn_registry/worktrees/<slug>
# 2. Scaffold la app via pipeline canonico
./fn run init_cpp_app <name> # apps C++
# o ./fn run init_jupyter_analysis ... # analysis
# o crear apps/<name>/ a mano (Go service, etc.)
# 3. ANTES de salir del worktree: inicializa la app como sub-repo
cd apps/<name>
git init -b master
git add -A
git -c user.email="agent@fn_registry" -c user.name="agent" \
commit -m "feat: initial scaffold of <name>"
# 4. Trabajo continua en sub-repo (commits dentro de apps/<name>/.git)
# 5. Cerrar issue en repo padre (mv .md a completed/), commit del padre con cambios en cpp/CMakeLists.txt, etc.
```
Cuando el humano corre `/full-git-push` despues del merge, el script `ensure_repo_synced_bash_infra` detecta que `apps/<name>/.git` existe + no tiene remote + crea repo Gitea en `dataforge/<name>` + pushea master.
### Que ESTA SI versionado en el repo padre
- `cpp/CMakeLists.txt` (el `if(EXISTS ...) add_subdirectory(apps/<name>) endif()`).
- `dev/issues/completed/<NNNN>-<slug>.md` (cierre del issue).
- `docs/capabilities/*.md` si la app aporta a un capability group.
- `dev/feature_flags.json` si introduce flags.
Todo lo demas (codigo de la app + app.md + appicon + service unit + tests propios de la app) vive en `apps/<name>/.git` independiente.
### Sintomas de la perdida
Si limpias el worktree y luego corres `ls apps/<name>/`, devuelve "No such file or directory" pese a que el issue aparece cerrado en `dev/issues/completed/`. **Patron** = scaffold sin sub-repo init = trabajo perdido.
### Recovery si pasa
1. Re-crear worktree desde master.
2. Re-spawn agente con instruccion explicita: **`git init` dentro de la app antes de terminar**.
3. NO eliminar el worktree hasta confirmar que `apps/<name>/.git` esta inicializado con al menos un commit.
### Aplica tambien a analysis
`analysis/*/` y `projects/*/analysis/*/` siguen mismo patron (cada analysis es repo Gitea). El pipeline `init_jupyter_analysis_bash_pipelines` ya hace `git init` automatico — por eso no hubo perdidas alli. Las apps C++/Go scaffolded a mano NO inicializan el sub-repo automaticamente — es responsabilidad del agente.
### Lo que aprende `parallel-fix-issues`
El template del prompt de cada agente DEBE incluir la instruccion:
> "Si tu issue crea una app nueva en `apps/<name>/`, inicializa el sub-repo (`cd apps/<name> && git init -b master && git add -A && git commit ...`) antes de terminar. Sin esto, `apps/*` esta gitignored y el codigo se perdera cuando el orquestador limpie el worktree."
Aplicar este parrafo al template del skill — ver `.claude/skills/parallel-fix-issues/SKILL.md` (o equivalente).
### Relacion con otras reglas
- [[apps_tbd]] — TBD en apps, esta regla complementa con el patron de sub-repo init.
- [[artefactos]] — apps son artefactos, esta regla especifica gotcha de su sub-repo.
- [[apps_vs_functions]] — apps en `apps/`, esta regla refuerza por que apps/* gitignored.
+102
View File
@@ -0,0 +1,102 @@
## Bucle autonomo (`fn-orquestador` + `/autonomous-task`) — issue 0069
`fn-orquestador` recorre el ciclo reactivo (CONSTRUIR → EJECUTAR → RECOPILAR → ANALIZAR → MEJORAR) sin intervencion humana, hasta convergencia (suite verde), estancamiento (no progreso N iteraciones), timeout, o tope de iteraciones. Trabaja SIEMPRE en sandbox `auto/<issue>`, NUNCA merge a master.
### Cuando se invoca
- Skill `/autonomous-task <issue_id>` (humano lanza explicitamente).
- Cron / dag_engine (`schedule:` en YAML; planificable, no implementado por defecto).
- NO se invoca como reaccion a hooks ni a fallos de tests "en caliente". Siempre tarea explicita.
### Reglas duras
1. **Sandbox obligatorio**: rama `auto/<issue_id>-<slug>`. Si la rama existe -> reset hard contra master y reanudar. NUNCA commits a master, NUNCA push --force-with-lease a master.
2. **Paths protegidos**: respetar `dev/autonomous_protected_paths.json` exactamente. Cualquier intento de modificar un path protegido aborta la iteracion y registra `task_runs.status='aborted_protected_path'`.
3. **Filtro de proposals auto-aplicables**: el orquestador SOLO aplica proposals que cumplen:
- `kind in (bug_fix, e2e_check_add, doc_update, capability_tag_add)` -> auto-aplicable.
- `kind in (new_function, deprecate_function, refactor, schema_change)` -> NO auto-aplicable (queda `pending` para humano).
- `priority in (low, medium)` -> auto-aplicable. `high|critical` -> requiere humano salvo override `--allow-high`.
4. **Watchdog**: si la metrica de progreso (`checks_pass / checks_total`) no sube en `N=3` iteraciones consecutivas -> abort. Registrar `task_runs.status='stalled'`.
5. **Tiempo**: cada `task_run` con timeout default 30 min. Override con `--timeout-min N` hasta max 4h.
6. **Idempotencia**: re-ejecutar `/autonomous-task <id>` sobre la misma issue reanuda desde la ultima iteracion exitosa, NO reinicia desde cero (lookup en `task_runs` por `issue_id`).
7. **Trazabilidad**: cada decision se persiste en `task_runs.events_json[]` con `{ts, agent, action, evidence, diff_summary}`. El humano puede leer el log entero para auditar.
8. **No self-modification**: orquestador NUNCA modifica `.claude/agents/`, `.claude/commands/`, `.claude/rules/`, `.claude/scripts/`, `.claude/CLAUDE.md`. Reforzado en `autonomous_protected_paths.json`.
9. **NUNCA paths absolutos fuera del worktree**. Refuerzo del piloto 1 (2026-05-15): el orquestador uso `/home/lucas/fn_registry/bash/functions/...` para fixear hooks bash y contamino el repo principal. Solucion correcta: fix vive solo en el worktree. Post-cada-iteracion: `git -C <main_repo> status --short` debe permanecer igual al baseline; cualquier diff = `status=sandbox_breach` -> ABORT.
10. **Pre-commit hooks compartidos**. Worktrees comparten `.git/hooks/` con main. Si un hook llama scripts via path absoluto, ejecutara la version de main. Si el hook bloquea progreso por bug en main: aplica el fix EN EL WORKTREE (commit en auto/*); si el bug del hook excede scope: `git commit --no-verify` para ESE commit con `task_runs.events_json[].decision="skip_hook"` + razon. NO editar main.
### Sub-repos vs worktree padre
Cuando el issue toca `app.md` o codigo dentro de `apps/<name>/`, `projects/<p>/apps/<name>/`, `cpp/apps/<name>/`, o `analysis/<a>/` — estos directorios son **sub-repos Gitea independientes** y estan `.gitignore`d en el repo padre `fn_registry` (regla `apps_subrepo.md`). El orquestador:
- **Crea worktree padre** `auto/<issue>` en `/tmp/fn_orq_<issue>_<ts>/` por protocolo, **pero no escribe alli** porque los cambios no se versionan en el padre.
- **Opera DIRECTAMENTE en el sub-repo** de la app/analysis target. Branch `auto/<issue>-<slug>` se crea dentro de `apps/<name>/.git`, NO en el padre.
- **PR draft sale al sub-repo** en `dataforge/<name>` (NO a `dataforge/fn_registry`). Humano revisa+mergea en el sub-repo.
- **Worktree padre queda vacio** y se limpia normal con `git worktree remove` al terminar.
Validado en piloto 0120 (`add_e2e_check` sobre `chart_demo`): PR creado en `dataforge/chart_demo/pulls/1`, sanity check del main repo `fn_registry` confirmo cero contaminacion.
Si el issue toca AMBOS lados (codigo del registry padre + app de sub-repo), el orquestador commitea separado: cambios del padre en `auto/<issue>` (worktree padre), cambios de la app en `auto/<issue>-<slug>` (sub-repo). Dos PRs draft. Humano coordina merge.
### Gitea API vs `gh`
Pre-condicion `gh auth status` es smoke check (target github.com). Mecanismo real de PR es `curl` a Gitea API:
```bash
GITEA_TOKEN=$(pass gitea/dataforge-git-token | head -n1)
curl -X POST -H "Authorization: token $GITEA_TOKEN" \
-H "Content-Type: application/json" \
-d '{"title":"...","head":"auto/<issue>-<slug>","base":"master","draft":true,"body":"..."}' \
"https://gitea-.../api/v1/repos/dataforge/<repo>/pulls"
```
Validado en pilotos 0076 y 0120.
### Estructura task_run
Migration `fn_operations/migrations/006_task_runs.sql`. Campos minimos: `id`, `issue_id`, `branch`, `started_at`, `finished_at`, `status` (`running|done|failed|aborted_protected_path|stalled|timeout`), `iterations`, `checks_pass`, `checks_fail`, `proposals_applied_json`, `proposals_skipped_json`, `events_json`, `final_diff_sha`.
### Fases por iteracion
```
loop:
1. fn-constructor (Read+Edit+Write+Bash limitados) - aplica fix segun ultima proposal seleccionada
2. fn-executor - corre build + tests + smoke
3. fn-recopilador - audita operations.db de la app
4. fn-analizador - corre e2e_checks (registra e2e_runs)
5. SI todos los checks pasan -> commit + push rama + abre PR. status=done. exit.
6. SI no progreso N iteraciones -> abort. status=stalled.
7. fn-mejorador - crea proposals desde fallos
8. orquestador filtra proposals auto-aplicables -> selecciona la primera -> goto 1.
```
### Output al humano
```
=== /autonomous-task 0068 ===
task_run_id: run_e2e_a1b2c3
branch: auto/0068-e2e-validation
iterations: 4
status: done
checks_pass: 8/8
proposals_applied: 3 (run_e2e_run_001, run_e2e_run_002, run_e2e_run_003)
proposals_skipped: 1 (refactor — needs human review)
PR: https://gitea.../pulls/42
```
### Anti-patrones
| Anti-patron | Por que es malo |
|---|---|
| Mergear `auto/<issue>` a master sin PR + humano | Salta gate, riesgo de regresion |
| Auto-aplicar proposal `kind=refactor` | Cambios sistemicos requieren revision |
| Modificar `go.sum`, `package-lock.json`, `uv.lock` | Cambios de deps requieren CVE/license review |
| Bucle infinito sin watchdog | Coste descontrolado de tokens |
| Borrar archivos sin backup en `task_runs.events_json` | Pierde auditoria |
| Override de paths protegidos via env var | Bypass de seguridad |
### Relacion con otras reglas
- [[e2e_validation]] — fn-analizador (fase 4) lee el contrato `e2e_checks` que el orquestador usa como gate.
- [[apps_tbd]] — el orquestador opera en rama `auto/*`, no exenta de TBD.
- [[feature_flags]] — si el fix no esta terminado, el orquestador puede meterlo detras de flag OFF antes de PR.
- [[registry_calls]] — toda invocacion del orquestador y sub-agentes pasa por MCP/`fn run`/heredoc canonico, registrada en call_monitor.
+60
View File
@@ -0,0 +1,60 @@
## Capability groups: tags + paginas madre en docs/capabilities/
Un **capability group** es un cluster de >=3 funciones del registry que comparten un dominio operativo (ej. `notebook`, `metabase`, `deploy`). Cada grupo tiene un **tag plano** (sin prefijo) y una **pagina madre** en `docs/capabilities/<grupo>.md`. La pagina madre desbloquea el conjunto entero en un solo read.
### Para que existen
Sin grupos, Claude redescubre funciones via FTS5 una a una cada sesion ("¿como interactuo con Jupyter? ¿como subo deploy?"). Con grupos, Claude lee `docs/capabilities/<grupo>.md` y carga las 5-10 funciones del cluster con su ejemplo canonico — menos turnos perdidos en discovery.
### Convencion de tag
- **Slug del grupo** = tag plano. Ej: `notebook`, `metabase`, `android-emu`.
- **No prefijos** (`cap:`, `group:`). Ya hay namespacing implicito porque convivirian con tags semanticos sueltos.
- **Una funcion puede llevar varios tags de grupo** si pertenece a dos clusters (raro pero valido).
- Filtro MCP: `mcp__registry__fn_search query="" tag="notebook"` lista el grupo.
### Cuando crear grupo nuevo
- **Minimo 3 funciones** afines. Con 2 no compensa pagina madre — quedan tags sueltos.
- **Dominio operativo claro**: el grupo debe ser describible en 1 frase ("operar Jupyter colaborativo", "deploy via SSH+systemd").
- **Frontera neta** con grupos existentes. Si solapa con otro -> reorganizar, no duplicar.
### Como crear grupo
1. Anadir el tag al frontmatter `.md` de >=3 funciones afines. `fn index` lo registra.
2. Crear `docs/capabilities/<grupo>.md` con plantilla:
- **Lista de funciones**: tabla `ID | firma corta | que hace`.
- **Ejemplo canonico**: 1-2 bloques de codigo end-to-end con los IDs reales.
- **Fronteras**: que NO cubre el grupo.
- **Prerequisitos** y **notas** si aplica.
3. Anadir fila al `docs/capabilities/INDEX.md`.
4. Correr `fn doctor capabilities` para auditar drift.
### Auto-generacion
`fn doctor capabilities --update` (TBD) reescribe la tabla de funciones de cada pagina madre preservando bloques curated (`Ejemplo canonico`, `Fronteras`, `Notas`). Las secciones curated nunca se sobrescriben.
### Como Claude usa los grupos
Cuando una tarea cae en un dominio conocido:
1. `Read docs/capabilities/INDEX.md` para localizar grupo.
2. `Read docs/capabilities/<grupo>.md` para cargar funciones + ejemplo.
3. Solo si el grupo no cubre lo necesario, `mcp__registry__fn_search` para funciones sueltas.
4. Si el grupo deberia cubrir pero falta funcion -> `fn-constructor` + tagear con el grupo en el frontmatter.
### Auditoria
```bash
fn doctor capabilities # lista grupos + drift
fn doctor capabilities --json # para agentes
```
Comprueba:
- Tag con N >=3 funciones pero sin pagina madre -> "tag huerfano".
- Pagina madre sin tag respaldo -> "grupo fantasma".
- Funcion con tag de grupo pero la pagina madre no la lista (autogen desfasada) -> "drift".
### Relacion con dominios
Los **dominios** del registry (`core`, `infra`, `finance`, `datascience`, `cybersecurity`, `shell`, `tui`, `pipelines`, `browser`) son taxonomia ortogonal — un grupo puede atravesar varios dominios (ej. `deploy` toca `infra` y `shell`). NO renombrar dominio a grupo ni viceversa.
+247 -12
View File
@@ -6,14 +6,28 @@
Esta regla NO duplica esos documentos — los señala como obligatorios y añade convenciones estructurales que no aparecen alli.
### 1. Ubicacion
### Scaffolder canonico — OBLIGATORIO
**REGLA DURA:** crear apps C++ nuevas SIEMPRE con `fn run init_cpp_app <name> [--project <p>] [--desc "..."]`. NUNCA escribir `main.cpp` + `CMakeLists.txt` + `app.md` desde cero a mano en `cpp/apps/` ni `projects/*/apps/`. Tampoco copiar otra app y renombrar — la deriva entre patrones es lo que estamos eliminando.
Si el scaffolder no cubre un caso (ej. necesitas plantilla diferente, layout custom desde el primer dia), **modificas el scaffolder**, no escribes la app a mano. La plantilla canonica es codigo, no decoracion.
Razones:
- Garantiza `cfg.about` + `cfg.log` + `cfg.panels` + framework defaults aplicados.
- Genera frontmatter `app.md` valido (framework, dir_path, repo_url) para `fn index`.
- Registra `add_subdirectory` en `cpp/CMakeLists.txt` (raiz o bloque `_DIR` para projects).
- Crea repo Gitea `dataforge/<name>` con master + commit inicial.
Pipeline: `init_cpp_app_bash_pipelines`. Slash command equivalente: `/new-cpp-app`. Auditoria: `fn doctor cpp-apps`.
### 1. Ubicacion (issue 0096 estandarizada)
| Caso | Donde vive |
|---|---|
| App independiente | `cpp/apps/<nombre>/` |
| App independiente | `apps/<nombre>/` |
| App de un proyecto | `projects/<proyecto>/apps/<nombre>/` |
NUNCA en `cpp/apps/<nombre>/` si pertenece a un proyecto, NUNCA fuera de `apps/` directamente. Ver `apps_location` en memoria + regla `apps_vs_functions.md`.
NUNCA en `cpp/apps/<nombre>/` (deprecado tras issue 0096) ni en cualquier otra carpeta nombrada por lenguaje (`python/apps/`, `bash/apps/`, etc.). Las carpetas por lenguaje son solo para codigo del registry (`cpp/functions/`, `python/functions/`, etc.), nunca para artefactos. Ver `apps_location` en memoria + regla `apps_vs_functions.md`.
### 2. Estructura minima
@@ -70,6 +84,7 @@ Plantilla minima para apps C++:
name: <name>
lang: cpp
domain: <gfx|tui|tools|infra|...>
version: 0.1.0 # semver per-app, bumped via /version
description: "Frase corta — lo que hace y por que existe."
tags: [imgui, ...] # si es service, anadir 'service'
uses_functions: # IDs del registry — el indexer NO deduce C++
@@ -88,6 +103,7 @@ Reglas:
- `framework: "imgui"` siempre que use `fn::run_app`. Otros valores solo si la app NO usa el shell (raro).
- `tags`: incluir `service` si es daemon de larga duracion (ver `function_tags.md`).
- `repo_url` apunta al sub-repo en Gitea (ver §6).
- `version`: semver per-app. Baseline `0.1.0` para apps nuevas. Bump obligatorio via `/version apps/<name> {major|minor|patch} "<reason>"` cuando `/fix-issue` toque codigo de la app. Trazabilidad humana en seccion `## Capability growth log` al final del `app.md` (una linea por bump). Ver `.claude/commands/version.md`.
### 5. Registro en `cpp/CMakeLists.txt`
@@ -175,20 +191,105 @@ WMs). Activado por defecto, sin opt-in:
con `glfwSetWindowPos/Size` (no espera al siguiente NewFrame).
2. **Per-frame viewport sync** al inicio del main loop — cubre viewports
secundarios (paneles drag-out) que la backend crea dinamicamente.
3. **Win32 WndProc subclass** (`#ifdef _WIN32`) — observa `WM_ENTERSIZEMOVE`
/ `WM_EXITSIZEMOVE` que AltSnap fakea alrededor de cada drag. Mientras
el bracket esta abierto el main loop SKIPEA `render_fn` + `glfwSwapBuffers`,
replicando el contrato del title-bar drag native (DefWindowProc bloquea
el hilo, DWM compositor mueve el framebuffer existente).
3. **Win32 WndProc subclass per HWND** (`#ifdef _WIN32`) — observa
`WM_ENTERSIZEMOVE` / `WM_EXITSIZEMOVE` que AltSnap fakea alrededor de cada
drag. El subclass se instala en la ventana principal Y en cada HWND
secundario que el backend de ImGui crea cuando un panel se arrastra fuera
del main (escaneo per-frame de `pio.Viewports`). Mientras el bracket esta
abierto en CUALQUIER HWND propio, el main loop SKIPEA `render_fn` +
`glfwSwapBuffers` globalmente, replicando el contrato del title-bar drag
native (DefWindowProc bloquea el hilo, DWM compositor mueve el framebuffer
existente). El flag `g_in_sizemove` es global a proposito: una sola
sesion de sizemove externo pausa todo el render para que ninguna ventana
compita con el OS.
Tests: `cpp/apps/altsnap_jitter_test/` corre dos fases:
Estado del subclass:
- `g_subclassed` = `unordered_map<HWND, WNDPROC>`. Chain a la proc
original via `CallWindowProcW`.
- `install_sizemove_subclass_hwnd(HWND)` idempotente (skip si ya en mapa).
- Per-frame: `prune_dead_subclassed()` con `IsWindow` + install en cada
`pio.Viewports[i]->PlatformHandle` nuevo.
- `uninstall_sizemove_subclass_all()` restaura cada HWND al exit.
#### Iconified main no pierde paneles flotantes (2026-05-16)
El legacy `glfwWaitEvents + continue` al detectar `GLFW_ICONIFIED` paraba TODO
el frame loop. Con multi-viewport activo eso significa que
`ImGui::UpdatePlatformWindows + RenderPlatformWindowsDefault` dejan de
refrescar los viewports secundarios — los floating panels aparecen congelados
o son agrupados/ocultados por el WM. Fix actual: el iconified-gate cuenta
viewports secundarios primero; si hay alguno, fall-through al frame normal
(la swap del main HWND minimizado es harmless, los contexts GL secundarios
siguen pintando). Solo cuando NO hay flotantes dormimos en `glfwWaitEvents`.
#### Alt + RMB / Alt + LMB anywhere → modal nativo (2026-05-16)
WndProc del subclass tambien intercepta clicks con Alt held (`GetAsyncKeyState(VK_MENU) & 0x8000`):
- `WM_LBUTTONDOWN` + Alt → `ReleaseCapture()` +
`PostMessage(WM_SYSCOMMAND, SC_MOVE | HTCAPTION)`. Modal MOVE nativo.
- `WM_RBUTTONDOWN` + Alt → calcula direccion por cuadrante (TOPLEFT/TOPRIGHT/
BOTTOMLEFT/BOTTOMRIGHT relativo al centro del client rect) y emite
`PostMessage(WM_SYSCOMMAND, SC_SIZE | dir)`. Modal RESIZE nativo.
Ambos retornan 0 (consumen el click — ImGui NO lo ve). Aplica a main y a
cada viewport flotante porque el subclass per-frame ya cubre todos los HWND.
El modal nativo dispara `WM_ENTERSIZEMOVE`, que el gate existente pausa
render → cero jitter automatico, mismo contrato que el title-bar drag.
**Caveat**: cualquier Alt+click se consume — perdes Alt+click como shortcut
UI. Aceptable porque Alt-modifier en clicks UI es muy raro.
#### Title-bar-only move para ImGui windows (2026-05-16)
`fn::run_app` setea `io.ConfigWindowsMoveFromTitleBarOnly = true`. Critico
para viewports secundarios: un viewport flotante = OS window borderless con
UNA ventana ImGui rellenandolo. Sin el flag, ImGui mueve sus ventanas
arrastrando cualquier client-pixel — como la ventana ImGui ES el viewport
entero, el OS window sigue al cursor sin modifier. Con el flag, floating
panels obedecen el contrato "solo header arrastra" (igual que main que tiene
title bar nativo de Windows). Alt+LMB anywhere sigue funcionando (consumido
antes por el subclass).
#### Test observability — `fn::internal::*` (2026-05-16)
Counters monotonicos para validar el subclass desde tests headless,
zero-cost en prod:
```cpp
namespace fn::internal {
int sizemove_enter_count(); // ++ en cada WM_ENTERSIZEMOVE
int alt_rmb_resize_count(); // ++ en cada Alt+RMB consumido
int alt_lmb_move_count(); // ++ en cada Alt+LMB consumido
int rbuttondown_seen_count(); // diagnostico — todo WM_RBUTTONDOWN
void set_force_alt_for_test(bool); // bypass GetAsyncKeyState para tests
}
```
En test mode (`set_force_alt_for_test(true)`), los handlers de Alt cuentan
pero NO postean `SC_SIZE`/`SC_MOVE` — el harness no se queda atrapado en el
modal de Windows. Path real en prod sigue posteandolos.
Tests: `apps/altsnap_jitter_test/` corre seis fases:
- `p1.sync` (cross-platform): drives `glfwSetWindowPos` cada frame, asserta
`vp->Pos` sigue OS dentro de 1px.
- `p2.altsnap` (Windows): worker thread fakea `WM_ENTERSIZEMOVE` +
burst de `SetWindowPos(SWP_ASYNCWINDOWPOS)` + `WM_EXITSIZEMOVE`, asserta
que `render()` no se llama durante el bracket.
burst de `SetWindowPos(SWP_ASYNCWINDOWPOS)` + `WM_EXITSIZEMOVE` sobre el
HWND principal, asserta que `render()` no se llama durante el bracket.
- `p3.secondary` (Windows): fuerza viewport secundario
(`ConfigViewportsNoAutoMerge=true`), localiza su HWND y repite el bracket
sobre el. Valida que el subclass per-viewport tambien pausa el render.
- `p4.minimize` (Windows): state machine 4 steps — captura
`IsWindow(secondary_hwnd)` antes/durante/despues de `glfwIconifyWindow +
glfwRestoreWindow`. Asserta los 3 estados vivos y `renders_iconified > 0`.
- `p5.alt_rmb` (Windows): `set_force_alt_for_test(true)` +
`SendMessage(WM_RBUTTONDOWN)` sincrono mismo-hilo. Asserta
`alt_rmb_resize_count` incrementa.
- `p6.alt_lmb` (Windows): mismo patron para `WM_LBUTTONDOWN`. Asserta
`alt_lmb_move_count` incrementa.
Lanzar con `e2e_run_cpp_windows altsnap_jitter_test`.
Lanzar con `source bash/functions/infra/e2e_run_cpp_windows.sh &&
e2e_run_cpp_windows altsnap_jitter_test`.
NO hace falta nada en cada app — toda `fn::run_app` lo hereda. Si una app
necesita renderizar incluso durante external move (caso raro: telemetria
@@ -247,3 +348,137 @@ de antes: `imgui.ini` es la unica fuente.
- App headless / capture mode: `cfg.auto_layouts = false`.
- Cambiar nombre del archivo: `cfg.auto_layouts_db = "<algo>.db"` (relativo a
`local_files/`).
### 11. Icono Windows (.ico embebido en el .exe) — 2026-05-16
Cada app C++ desplegada a Windows tiene su propio icono. El icono vive en
`<app_dir>/appicon.ico` (multi-resolucion: 16/24/32/48/64/128/256). El macro
`add_imgui_app` de `cpp/CMakeLists.txt` lo detecta automaticamente: si
`WIN32` + existe `<CMAKE_CURRENT_SOURCE_DIR>/appicon.ico`, genera un
`<target>_appicon.rc` en `CMAKE_CURRENT_BINARY_DIR` apuntando al `.ico` con
`IDI_ICON1 ICON "<path>"` y lo anade a `add_executable`. El compilador RC
(`x86_64-w64-mingw32-windres` configurado en `cpp/toolchains/mingw-w64.cmake`)
lo enlaza al `.exe` como recurso `.rsrc`.
Verificar: `x86_64-w64-mingw32-objdump -h <app>.exe | grep rsrc` debe
mostrar la seccion. El project line en `cpp/CMakeLists.txt` declara
`LANGUAGES C CXX RC` solo en WIN32 (Linux ignora la `.rc`).
#### Crear `.ico` para una app nueva
Fuente de glyphs: **Phosphor Icons** (`sources/phosphor-core/`, clonado de
`https://github.com/phosphor-icons/core.git`). 1512 SVGs en weight `regular`,
`bold`, `fill`, `light`, `thin`, `duotone`. Usamos `fill` por defecto — mejor
legibilidad a 16/24px.
Funcion del registry: `generate_app_icon_py_infra` rasteriza un SVG Phosphor
sobre fondo redondeado del color accent y exporta `.ico` multi-res. Una
linea por app:
```python
from infra import generate_app_icon
generate_app_icon(
phosphor_icon_name="chart-bar",
accent_hex="#0ea5e9",
out_ico_path="apps/chart_demo/appicon.ico",
)
```
Mapping vive en el frontmatter de cada `app.md` C++:
```yaml
description: "Frase corta de 1 linea — que hace la app y por que existe."
icon:
phosphor: "chart-bar"
accent: "#0ea5e9"
```
### Trio obligatorio: description + icon.phosphor + icon.accent
**REGLA DURA:** TODA app C++/imgui declara los **3 campos JUNTOS** en su `app.md`:
1. `description:` (string corta, 1 linea) — texto que el `app_hub_launcher` muestra en la tarjeta y que el dashboard usa para tooltips.
2. `icon.phosphor:` (nombre del glyph Phosphor sin sufijo `-fill`) — glyph del icono.
3. `icon.accent:` (hex `#rrggbb`) — color del fondo redondeado del icono **Y** color del boton/border de la tarjeta en `app_hub_launcher`.
Los 3 se consumen como un set unico: el icono visual + el texto + el color de marca de la app. Una app sin descripcion aparece como tarjeta gris sin texto; sin `icon:` cae al default (`app-window` slate); sin accent el boton del hub aparece blanco. **Documentar uno sin los otros es bug**, no estilo.
### Refrescar el App Hub tras editar el trio
`app_hub_launcher` cachea iconos (PNG) y manifest (TSV) al arrancar. Cambiar `description`/`icon.*` en un `app.md` requiere regenerar ambos sidecars + relanzar el hub. Pipeline canonico:
```bash
./fn run refresh_app_hub # icons + manifest + restart hub
./fn run refresh_app_hub --no-restart # solo regenera, util si el hub esta cerrado
./fn run refresh_app_hub --size 128 # PNGs 128px en vez de 64
```
ID: `refresh_app_hub_bash_pipelines`. Compone `export_hub_icons_py_infra` + `export_hub_manifest_py_infra` + `is_cpp_app_running_windows_bash_infra` + `launch_cpp_app_windows_bash_infra`.
Regeneracion batch via pipeline del registry — escanea `app.md`s y compone
`generate_app_icon` por app. Anadir app nueva: declarar `icon:` en su
`app.md` y lanzar:
```bash
./fn run regenerate_app_icons # todas
./fn run regenerate_app_icons chart_demo # solo una
```
Convenciones:
- **Glyph weight**: `fill` (mas legible a 16px que `regular` o `bold`).
- **Color**: 1 accent_hex distinto por app — Tailwind palette 500-700
funciona bien (`#0ea5e9` sky-500, `#16a34a` green-600, etc.).
- **Padding**: glyph ocupa ~70% del canvas, fondo redondeado al 16% del lado.
- **Glyph color**: siempre blanco sobre el fondo accent.
Si Phosphor no tiene el icono adecuado: buscar en `sources/phosphor-core/assets/fill/`
con `ls | grep <keyword>` antes de inventar — 1512 disponibles.
#### Re-deploy tras cambiar icono
```bash
# 1. Editar icon: en apps/chart_demo/app.md y regenerar
./fn run regenerate_app_icons chart_demo
# (o ./fn run generate_app_icon "chart-bar" "#0ea5e9" "apps/chart_demo/appicon.ico" para uno suelto sin tocar app.md)
# 2. Rebuild + redeploy (build dispara windres → nuevo .rsrc)
./fn run redeploy_cpp_app_windows chart_demo apps/chart_demo --build
```
Windows cachea iconos en `iconcache.db`. Si el nuevo icono no aparece tras
desplegar, refresh con `ie4uinit.exe -show` o reiniciar Explorer.
#### Runtime attach: taskbar + title bar + Alt+Tab (2026-05-16)
Embeber `.ico` en el `.exe` (windres) basta para File Explorer / shortcuts —
pero GLFW crea su WNDCLASS sin icono, asi que la **barra de tareas**, el
**header de la ventana** y **Alt+Tab** muestran el icono GLFW por defecto a
menos que adjuntemos el recurso al HWND en runtime.
`fn::run_app` lo hace automaticamente, sin opt-in. Tras `glfwCreateWindow`:
```cpp
HICON hSmall = LoadImageW(GetModuleHandleW(NULL), MAKEINTRESOURCEW(101),
IMAGE_ICON, GetSystemMetrics(SM_CXSMICON),
GetSystemMetrics(SM_CYSMICON), LR_SHARED);
HICON hBig = LoadImageW(..., SM_CXICON, SM_CYICON, LR_SHARED);
SendMessageW(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)hSmall); // title bar
SendMessageW(hwnd, WM_SETICON, ICON_BIG, (LPARAM)hBig); // taskbar
SetClassLongPtrW(hwnd, GCLP_HICONSM, (LONG_PTR)hSmall);
SetClassLongPtrW(hwnd, GCLP_HICON, (LONG_PTR)hBig);
```
Resource ID `101` lo emite `add_imgui_app` en el `.rc` generado
(`101 ICON "<app_dir>/appicon.ico"`). Si la app no tiene `appicon.ico`, el
`.rc` no se genera, `LoadImageW` devuelve NULL y el HWND queda con el icono
GLFW por defecto (sin error).
Cobertura multi-viewport: el per-frame scan de `pio.Viewports` (mismo que
instala el sizemove subclass) tambien llama `attach_app_icon_to_hwnd` sobre
cada HWND secundario nuevo. Floating panels dragged-out heredan el icono
sin codigo extra en la app.
Cache shell: el pipeline `redeploy_cpp_app_windows` llama
`refresh_windows_icon_cache_bash_infra` tras copiar el .exe — invoca
`ie4uinit.exe -show` para que Explorer recargue `iconcache.db` sin esperar
a que detecte el cambio por timestamp. Si Explorer sigue mostrando el
icono viejo: borrar `%LOCALAPPDATA%\IconCache.db` + reiniciar Explorer.
+42
View File
@@ -0,0 +1,42 @@
## Delegacion: spawn fn-constructor en vez de escribir inline
**REGLA DURA.** Si vas a escribir logica reutilizable inline en un artefacto (app, analysis, playground) o heredoc, STOP y delega a `fn-constructor`. La misma sesion debe crear + usar la funcion. No acumular huerfanas.
### Cuando un patron es candidato a funcion
- Aparece >=2 veces en esta sesion o en heredocs recientes.
- Firma generica (no depende de tipos internos del artefacto).
- 1 responsabilidad clara (CRUD, parse, transform, http call, formato fijo, etc.).
- No es one-liner idiomatico de stdlib (`time.Now().UTC().Format(...)` queda fuera).
### Flujo obligatorio (mismo turno)
1. **Detectar**. Si vas a escribir >=5 lineas de logica reutilizable inline -> STOP.
2. **Spawn `fn-constructor` inmediato** via `Agent(subagent_type="fn-constructor", ...)`:
- **Sin preguntar al usuario** (autorizado por defecto).
- Si hay >1 funcion independiente -> una sola llamada al Agent tool con **N tool_use blocks paralelos** en el mismo mensaje. NO serializar.
3. **Tagear con grupo de capacidad** al menos UN tag de grupo (`notebook`, `metabase`, `deploy`, etc.). Ver `capability_groups.md`.
4. **`fn index`** para registrar.
5. **Importar + invocar en el mismo turno** — no dejar funcion huerfana recien creada.
6. **Auto-verificar** con `fn doctor uses-functions` y `fn doctor unused` si tocas >=3 funciones nuevas.
### Anti-patrones auditables
| Anti-patron | Consecuencia | Sustituir por |
|---|---|---|
| Escribir helper inline en artefacto en vez de delegar | Reinvento por sesion | Spawn fn-constructor |
| Crear N funciones serialmente | Latencia x N | Multiples `Agent()` en mismo mensaje |
| Crear funcion y no usarla en el turno | Huerfana desde dia 1 (`calls_90d=0`) | Importar + invocar antes de cerrar turno |
| Crear funcion sin tag de grupo | Imposible descubrir en bloque proxima sesion | Anadir tag de grupo (capability group) |
| Reescribir en heredoc logica que ya existe | Capitalizacion perdida | `mcp__registry__fn_search` antes de escribir |
### Excepciones
- **Logica de dominio especifica del artefacto** (CRUD de tabla concreta, layout de UI, flujo unico de la app) -> queda en el artefacto. Solo lo reutilizable se delega.
- **Stub temporal con `not implemented`**: aceptable si la dependencia externa no esta disponible. Documentar en `.md` (ver `stubs.md`).
### Telemetria
Cada `code_writes` + `calls` se registra en `call_monitor/operations.db` (issue 0085). Vista `session_capability_growth` mide ratio creadas vs usadas por sesion. Hook `UserPromptSubmit` inyecta `CAPABILITY-GROWTH: created_this_session=X used=Y orphan=Z` en cada turno.
Si `orphan>0` al cerrar la sesion -> revisar: o la funcion era especulativa (no debio crearse) o falta integrarla en el codigo del artefacto.
+18 -1
View File
@@ -13,16 +13,25 @@
### Comandos
```bash
fn doctor # Corre TODOS los checks (artefacts + services + sync + uses-functions + unused)
fn doctor # Corre TODOS los checks (artefacts + services + sync + uses-functions + unused + cpp-apps)
fn doctor artefacts # Solo artefactos: git/venv/app.md/upstream
fn doctor services # Solo apps con tag 'service' + systemctl + puerto
fn doctor sync # Solo drift pc_locations BD vs disco local
fn doctor uses-functions # Solo audit imports reales vs uses_functions
fn doctor unused # Solo funciones huerfanas del registry
fn doctor cpp-apps # Conformidad C++ con cpp/PATTERNS.md (cfg.about/log, no app_menubar manual, no DockSpace duplicado)
# + check BeginTable inline: CANDIDATE (no migrado) / MIXED (parcial) / silencio (limpio)
fn doctor --json # Salida JSON (cualquier subcomando) — para agentes/scripts
```
`fn doctor cpp-apps` produce dos secciones:
1. Conformance (cfg.about/log, fn::run_app, menubar, DockSpace) — una fila por app imgui.
2. BeginTable migration (issue 0081) — solo apps con `ImGui::BeginTable` inline:
- `CANDIDATE`: N tablas inline sin `data_table_cpp_viz` en uses_functions. Considerar migracion.
- `MIXED`: N tablas inline con `data_table_cpp_viz` ya declarado. Migracion parcial OK.
- silencio: 0 BeginTable inline (limpio o completamente migrado).
### Mapeo subcomando → funcion del registry
| Subcomando | Funcion |
@@ -32,6 +41,8 @@ fn doctor --json # Salida JSON (cualquier subcomando) — para agentes
| `sync` | `pc_locations_drift_go_infra` |
| `uses-functions` | `audit_uses_functions_go_infra` |
| `unused` | `find_unused_functions_go_infra` |
| `cpp-apps` (conformance) | `audit_cpp_apps_go_infra` |
| `cpp-apps` (table migration) | `audit_cpp_table_migration_go_infra` (inline en `audit_cpp_apps.go`) |
Cada subcomando es un wrapper fino. Toda la logica vive en la funcion. Si quieres usar la salida en otro programa Go, importa la funcion directamente.
@@ -58,6 +69,12 @@ Texto humano por defecto (tabwriter). `--json` produce array/objeto serializable
| `port not listening` | `port_kill_bash_infra <port>` (si zombie) y relanzar |
| `missing_in_app_md` | Editar `app.md` y añadir el ID a `uses_functions` |
| `unused` (funcion huerfana) | Decidir: usar, deprecar (tag), o borrar |
| `manual_app_menubar_call` | Borrar `fn_ui::app_menubar(...)` del render — el framework ya lo dibuja |
| `manual_DockSpaceOverViewport_*` | Borrar la llamada o setear `cfg.auto_dockspace = false` si la app gestiona docking propio |
| `missing_cfg_about` / `missing_cfg_log` | Anadir `cfg.about = {...}` / `cfg.log = {"<name>.log", 1}` antes de `fn::run_app` |
| `app.md_missing_*` | Regenerar via plantilla del scaffolder (`/new-cpp-app`) o anadir campos a mano |
| cpp-apps BeginTable `CANDIDATE` | App tiene N `ImGui::BeginTable` sin migrar. Abrir rama TBD, reemplazar tablas por `data_table::render()` via `fn_table_viz`, añadir `data_table_cpp_viz` a `uses_functions` en `app.md` |
| cpp-apps BeginTable `MIXED` | Migracion parcial en curso. Continuar wave por wave hasta que no queden BeginTable inline |
| Backup viejo | `backup_all_bash_pipelines ~/backups/fn_registry` |
### Para agentes
@@ -0,0 +1,115 @@
## Function growth + self-documenting capability
Dos doctrinas hermanas. Una define **como deben ser** las funciones (auto-descubribles y lanzables sin segunda lectura). La otra define **como crece** el registry (no inflando funciones — promoviendo composiciones a pipelines).
Issue 0087.
---
### Parte A — `.md` autosuficiente (contrato OBLIGATORIO)
Cuando Claude (o un humano) encuentra una funcion via FTS / fuzzy match / capability page / TOP block, el `.md` debe bastar para **lanzarla sin abrir el codigo**. Esto es lo que hace que descubrir = lanzar y elimina el coste del second lookup.
**Secciones obligatorias** en cada `.md` del registry (functions + pipelines + types con uso practico):
| Seccion | Contenido | Tamaño |
|---|---|---|
| Frontmatter | `name`, `signature`, `params` (con `desc` por param), `output`, `tags`, `uses_functions`, etc. Lo de hoy. | — |
| `## Ejemplo` | Bloque de codigo lanzable con args **concretos**. Copiar+pegar produce ejecucion real. NO placeholders abstractos. | 3-10 lineas |
| `## Cuando usarla` | 1-2 frases con triggers: "cuando hagas X / antes de Y / si necesitas Z". Verbos imperativos. Ayuda al fuzzy match y a Claude a saber sin leer el codigo. | 1-3 lineas |
| `## Gotchas` | Problemas conocidos / no-go cases. Obligatoria para funciones impuras o con efectos (Windows-side, red, FS write, GPU). Omisible para funciones puras triviales. | 0-5 puntos |
| `## Capability growth log` | Solo SI la funcion ha crecido. Una linea por version: `v1.1.0 (YYYY-MM-DD) — anade --build flag para skip build`. No se rellena en v1.0.0. | crece con el tiempo |
**Anti-patrones del .md:**
- Ejemplo con `<arg1>`, `<arg2>` placeholders abstractos — NO. Ejemplos con valores reales (`registry_dashboard`, `/home/lucas/...`).
- "Cuando usarla" vacio o "ver descripcion arriba" — NO. Frase nueva con trigger explicito.
- `notes` lleno + `## Gotchas` vacio cuando la funcion tiene efectos — mover de `notes` a `## Gotchas`.
- Capability growth log inventado (sin que la funcion haya cambiado) — NO. Solo se rellena cuando hay version bump real.
**Verificacion** (TBD: convertir a check de `fn doctor`): cada .md de `functions/`/`pipelines/` debe tener `## Ejemplo` y `## Cuando usarla`. `## Gotchas` obligatoria solo si `purity: impure`. `## Capability growth log` libre.
---
### Parte B — Crecimiento por composicion (no por inflado)
**Principio:** una funcion que hace bien UNA cosa NO necesita crecer. Anadir params "por si acaso" la hace peor (Inner Platform Effect). Lo que crece es el **registry**: pipelines nuevos que componen funciones existentes.
#### Ejemplo del principio
- **Hoy:** Claude para hacer una transferencia bancaria llama `bank_login` -> `bank_list_accounts` -> `bank_make_transfer`. 3 calls, 3 decisiones, 3 puntos de fallo.
- **Manana:** pipeline `bank_transfer_oneshot(account, amount, target)` que compone las 3 internamente. 1 call, 1 decision.
Misma capacidad, 3x menos pasos. **Esto es lo que multiplica la velocidad de Claude**, no anadir flags a `bank_login`.
#### Como se promueve una composicion
Senal detectable en `call_monitor.operations.db`: secuencia A→B(→C) con
- **Mismo session_id**.
- **Intervalo entre calls < N segundos** (default 30s).
- **Occurrences > K** (default 5) en ventana de **D dias** (default 30).
- **Success rate > S** (default 0.9 — falla < 10%).
- **No existe ya un pipeline** que la cubra (validar con FTS sobre `uses_functions`).
Cuando se cumple → **proposal `new_pipeline`** con evidencia (sequence_ids, session_ids, occurrence count). Humano (o `fn-orquestador` autonomo) decide promover.
#### Implementacion (issue 0087 tanda A)
- `call_monitor sequences --detect` subcomando: escanea `calls` table, agrupa por session+window, computa secuencias, upserta en tabla `function_sequences`.
- Cron diario que ejecuta el detector + genera proposals automaticas.
- Visible en Monitor tab del `registry_dashboard`: sub-tab "Promotion candidates".
#### Cuando SI inflar una funcion
Casos legitimos para anadir feature a una funcion existente:
1. **Generalizar firma** sin romper consumidores (anadir param opcional con default sensato).
2. **Mejor manejo de error** (mensajes mas claros, retry sensible).
3. **Default mas inteligente** (autodetectar lo que antes era arg obligatorio).
4. **Eliminar gotcha conocido** (fix de bug que estaba en `## Gotchas`).
NO infles para casos hipoteticos. NO anadas params "por flexibilidad". Si dudas, separa la responsabilidad en una funcion nueva o un pipeline.
#### Capability growth log — cuando se rellena
- Se rellena **solo cuando la funcion crece** (alguno de los 4 casos arriba).
- Cada bump de `version` -> 1 linea en `## Capability growth log` con fecha y resumen 1-frase.
- Una funcion estable de hace 6 meses puede seguir en v1.0.0 sin log: indica madurez, no abandono.
- Telemetria (call_monitor) decide si una funcion estable es huerfana (`calls_90d=0`) o usada-y-buena (`calls_30d>10, error_rate<0.05`). Las primeras se deprecan; las segundas se respetan.
---
### Parte C — Output de discovery
Cuando un mecanismo de discovery (fuzzy match / FRESH hook / TOP block / capability page) surfacea una funcion, el payload **minimo** es:
```
<id> → <signature> → <ejemplo de 1 linea>
```
Ejemplo concreto:
```
redeploy_cpp_app_windows_bash_pipelines
./fn run redeploy_cpp_app_windows registry_dashboard /path/to/app [--build]
use: tras compilar cpp/build/windows, antes de smoke test manual
```
Si Claude necesita mas (gotchas, params completos, codigo), un `mcp__registry__fn_show <id>` adicional. Pero el primer hit ya basta para el 80% de casos.
---
### Parte D — Relacion con otras reglas
- [[registry_first]] dice CUANDO buscar/usar/delegar. Esta regla dice **COMO** debe ser la funcion para que esa busqueda valga.
- [[ids_naming]] hace ID predictible. Esta regla hace metadata predictible.
- [[delegation]] dice cuando spawnar fn-constructor. Esta regla es lo que fn-constructor debe producir.
- [[capability_groups]] agrupa funciones afines. Las paginas madre de cada grupo deben respetar el mismo contrato self-doc (mejor con su propio ejemplo end-to-end por grupo).
### Resumen TL;DR
1. Cada `.md` autosuficiente: Ejemplo + Cuando usarla + Gotchas (si impura) + Growth log (si crecio).
2. Las funciones que hacen bien una cosa NO necesitan crecer.
3. El registry crece **promoviendo composiciones repetidas a pipelines**, no inflando funciones.
4. Telemetria de `call_monitor` detecta secuencias candidatas y abre proposals automaticas.
5. Discovery devuelve siempre: `id + signature + 1-line example`. Resto on-demand.
+23
View File
@@ -28,3 +28,26 @@ Documentar en el `app.md` del service:
- El puerto que usa (si expone HTTP/gRPC)
- Como lanzarlo y pararlo
- Como comprobar que esta vivo (health check)
### Bloque `service:` obligatorio (issue 0105)
Toda app con `tag: service` declara el bloque `service:` en su frontmatter. El indexer lo persiste en columnas dedicadas de `apps` + tabla `service_targets`. Consumido por `services_api`/`services_monitor` (issue 0106) y por `fn doctor services-spec`.
```yaml
service:
port: 8484 # null si no expone HTTP (stdio, daemon sin API)
health_endpoint: /api/databases # ruta GET, 2xx/3xx = sano; null si no aplica
health_timeout_s: 3
systemd_unit: sqlite_api.service # obligatorio si runtime empieza con `systemd-`
systemd_scope: user # user|system|null (docker-compose)
restart_policy: always # always|on-failure|none
runtime: systemd-user # systemd-user|systemd-system|docker-compose|stdio|manual
pc_targets: # >=1, pc_id de pc_locations
- aurgi-pc
- home-wsl
is_local_only: false # true => no se monitoriza por SSH (siempre local)
```
Validacion: `fn doctor services-spec` (`functions/infra/audit_services_spec.go`). Hoy 11/11 services con bloque completo.
**Gotcha critico:** usar `Restart=always` (no `on-failure`) en el unit systemd. Un `SIGTERM` limpio es exit success → `on-failure` NO reinicia y el service se queda muerto silenciosamente. `sqlite_api.service` cayo 20h asi el 2026-05-17.
+34 -2
View File
@@ -1,3 +1,35 @@
IDs siguen el formato `{name}_{lang}_{domain}` (ej: `filter_slice_go_core`).
## ids_naming — formato predictible
Nombres de funciones en snake_case. Tipos en PascalCase para Go.
IDs: `{name}_{lang}_{domain}` (ej: `filter_slice_go_core`). Predictibilidad alta -> Claude descubre por fuzzy match sin lookup. Issue 0087.
### Reglas
1. **snake_case**: `[a-z0-9_]+`. Nada de PascalCase, kebab-case, dot.notation.
2. **Verbo obligatorio**: al menos un token del `name` debe ser un verbo de accion. El verbo puede ir delante (`get_user`) o detras (`user_lookup`). Ejemplos validos: `filter_slice`, `bank_login`, `metabase_get_dashboard`, `redeploy_cpp_app`. Invalidos: `slice` (sustantivo solo), `user` (sustantivo solo), `data` (sustantivo solo).
3. **Dominio canonico**: el `domain` debe estar en la lista canonica (ver `mcp__registry__fn_list_domains`). Crear dominio nuevo solo si el bucket es claramente distinto y se anade en el mismo turno a CLAUDE.md.
4. **Tipos en PascalCase Go**: `ResultGoCore`, `ErrorGoCore`. Aplica solo al codigo Go; el ID en el registry sigue siendo snake_case (`result_go_core`).
### Verbos canonicos (allowlist)
Lista no exhaustiva pero cubre la mayoria. Anadir aqui (y al validator en `apps/registry_mcp/naming.go`) cuando se introduzca un verbo nuevo recurrente.
`get, set, list, find, search, show, read, load, fetch, scan, query, lookup, parse, format, encode, decode, marshal, unmarshal, serialize, deserialize, validate, check, ensure, verify, audit, diagnose, test, match, filter, map, reduce, sort, group, count, sum, aggregate, compute, calculate, score, rank, cluster, classify, detect, init, create, make, build, generate, scaffold, install, setup, configure, register, add, insert, append, prepend, update, upsert, modify, edit, patch, replace, delete, remove, clear, drop, prune, clean, copy, move, rename, sync, clone, extract, inject, import, export, send, post, put, call, dispatch, exec, run, launch, start, stop, kill, restart, redeploy, deploy, open, close, connect, disconnect, login, logout, authenticate, enable, disable, toggle, lock, unlock, propose, promote, deprecate, approve, reject, emit, render, draw, paint, serve, host, pull, push, checkout, commit, tag, merge, rebase, watch, monitor, observe, log, trace, profile, benchmark, snapshot, backup, restore, archive, compress, decompress, hash, encrypt, decrypt, sign, taskkill, recopile, vault, propose, apply, gather, collect, fold, head, tail, take, drop, slice, chunk, batch, debounce, throttle, retry, await, sleep, ping, kill, prime, warm, refresh, invalidate, reload, reset, rollback, fork, spawn, daemon, observe, plot, draw, capture, replay, recopilate`
### Excepciones
- **Operadores matematicos/estadisticos** ampliamente reconocidos por acronimo: `sma`, `ema`, `rsi`, `vwap`, `adx`. Validator hace allowlist explicita.
- **Tipos** (entity_type `type`): no requieren verbo. Validator lo salta cuando `kind=type`.
- **Components** (`kind: component`): nombre describe artefacto UI (`button_primary`, `chat_panel`). Permite forma `<noun>_<modifier>`. Validator salta el check de verbo si `kind=component`.
### Validator
`mcp__registry__fn_create_function` ejecuta el validator antes de escribir archivos. Rechaza con error si:
- name no es snake_case.
- name no contiene verbo (excepto component/type).
- domain no esta en lista canonica.
Error tipico:
```
naming: name "slice" lacks action verb. Add verb prefix/suffix (e.g. filter_slice, slice_window). See .claude/rules/ids_naming.md.
naming: domain "bizops" not in canonical list (core, infra, finance, ...). Add it to CLAUDE.md and rules first.
```
+52
View File
@@ -0,0 +1,52 @@
## Slash commands por project (namespaced)
Cada `projects/<p>/` puede tener su propio `.claude/commands/*.md`. Para invocarlos desde la raiz de `fn_registry` sin que pisen los comandos globales, se exponen via **symlink namespaced** en `fn_registry/.claude/commands/<project>/`.
### Patron canonico
```
projects/aurgi/.claude/commands/foo.md # archivo real (viaja con el sub-repo del project)
fn_registry/.claude/commands/aurgi -> symlink -> ../../projects/aurgi/.claude/commands
```
Resultado:
| cwd | Invocacion |
|---|---|
| `cd projects/aurgi && claude` | `/foo` (sin namespace) |
| `cd fn_registry && claude` | `/aurgi:foo` (namespaced, no colisiona con `/foo` global) |
Subdirs dentro de `.claude/commands/` se exponen como namespace en el slash command. Por eso `aurgi/foo.md` -> `/aurgi:foo`.
### Como anadir un project nuevo
1. `mkdir -p projects/<p>/.claude/commands/`.
2. Crear `<comando>.md` con frontmatter `description:` + cuerpo.
3. Symlink: `ln -sf ../../projects/<p>/.claude/commands /home/egutierrez/fn_registry/.claude/commands/<p>`.
4. Versionar el `.claude/commands/` del project en su propio sub-repo (NO en fn_registry — projects estan gitignored).
5. Versionar SOLO el symlink en fn_registry (`git add .claude/commands/<p>`).
### Reglas
- Cada project mantiene autonomia: sus commands viajan con el sub-repo y funcionan tanto en `cd projects/<p>` como desde la raiz.
- El symlink en fn_registry da acceso global con namespace — sin colision con commands del registry.
- NO duplicar contenido: archivo real solo en `projects/<p>/.claude/commands/`. fn_registry solo guarda el symlink.
- Si el project se mueve/elimina, borrar el symlink en fn_registry.
### Listado actual
| Project | Symlink | Commands disponibles desde fn_registry |
|---|---|---|
| aurgi | `.claude/commands/aurgi` | `/aurgi:aumentar_task`, `/aurgi:contexto_aurgi`, `/aurgi:anadir_contexto_aurgi` |
Anadir filas aqui al introducir un project nuevo con commands.
### Catalogo dinamico
Para listado en tiempo real (sin tener que actualizar esta tabla a mano): `/commands` escanea `.claude/commands/` recursivo y agrupa por namespace. Filtros: `/commands <substring>`, `/commands --ns <ns>`, `/commands --json`.
### Gotchas
- Claude Code lista los commands disponibles al inicio de sesion. Si un symlink apunta a un directorio inexistente, los commands no aparecen — verificar con `ls -L .claude/commands/<project>/`.
- El namespace usa el nombre del subdirectorio (`aurgi/`), no del project en `projects/`. Mantenerlos iguales para evitar confusion.
- Los commands del project se ejecutan con el cwd de la sesion actual. Un `/aurgi:aumentar_task` invocado desde `fn_registry/` corre con cwd `fn_registry/` — paths relativos en el `.md` deben asumir esto (siempre usar paths relativos al repo, ej. `projects/aurgi/vaults/...`).
+147
View File
@@ -0,0 +1,147 @@
## Como invocar funciones del registry — patrones canonicos
Toda invocacion del agente al registry sigue uno de **tres patrones**. Cualquier otro patron es antipatron auditable. Las invocaciones se loguean en `projects/fn_monitoring/apps/call_monitor/operations.db` (issue 0085) para alimentar el bucle reactivo.
### Patrones canonicos
| Caso | Patron | Cuando |
|---|---|---|
| **Inspeccionar** (buscar, leer codigo, ver dependencias, listar dominios, leer proposals) | `mcp__registry__fn_search` / `fn_show` / `fn_code` / `fn_uses` / `fn_list_domains` / `fn_proposal` | SIEMPRE para descubrimiento, lectura de codigo, exploracion. |
| **Ejecutar** UNA funcion/pipeline con sus args | `mcp__registry__fn_run <id> [args]` (preferido) o `./fn run <id> [args]` (fallback CLI) | ID conocido + args planos. Despacho automatico por lenguaje. |
| **Componer** ad-hoc multi-funcion con logica intermedia | Heredoc `python/.venv/bin/python3 - <<'PYEOF' ... PYEOF` IMPORTANDO funciones del registry | Solo si hay loops/conditionals/dispatch entre N funciones. Las funciones del registry **se importan**, no se reescriben. |
### Antipatrones prohibidos (audit-targeted)
| Patron | Razon | Sustituir por |
|---|---|---|
| `sqlite3 registry.db "SELECT ..."` para buscar funciones/tipos | Salta MCP, FTS5 gotchas, sin trazabilidad | `mcp__registry__fn_search` |
| `sqlite3 registry.db "SELECT ... FROM proposals"` | Mismo problema | `mcp__registry__fn_proposal` |
| `python -c "import metabase; dir(metabase)"` para descubrir helpers | Fuente de verdad = registry, no `__init__.py` | `mcp__registry__fn_search "metabase"` + `mcp__registry__fn_show <id>` |
| Heredoc que reescribe logica que ya existe como funcion del registry | Reinvento + perdida de capitalizacion | Buscar primero; si falta, delegar a `fn-constructor` (no escribir inline) |
| `client._http.request(...)` saltando wrapper del registry | Salta validacion del wrapper y telemetria | Usar wrapper; si firma incompleta, `fn proposal add --kind improve_function` |
| Scripts en `temp/` para composiciones que se repiten >2 veces | Codigo perdido + sin monitoreo | Pipeline en `python/functions/pipelines/` o `bash/functions/pipelines/` |
| `from <pkg> import *` en heredoc | Imposible identificar funciones usadas | Imports explicitos `from <domain> import <name1>, <name2>` |
### Excepciones autorizadas para `sqlite3` directo
Casos donde el MCP no aplica y `sqlite3 registry.db` es legitimo:
- Introspeccion de schema: `.schema`, `.tables`, `PRAGMA table_info(...)`, `PRAGMA index_list(...)`.
- Agregaciones: `COUNT(*)`, `GROUP BY`, `SUM(...)`, `AVG(...)`.
- JOINs custom entre tablas que el MCP no expone (`functions JOIN unit_tests ON ...`).
- Columnas que el MCP no devuelve (rare; preferir proponer ampliacion del MCP).
El hook `PreToolUse` (`.claude/scripts/hook_registry_mcp.sh`) ya deja pasar estas excepciones y solo avisa cuando ve `sqlite3 registry.db "SELECT ..."` plano.
### Excepcion: hooks e infraestructura de telemetria (issue 0087)
Los **hooks** (`PreToolUse`, `PostToolUse`, `UserPromptSubmit`, etc.) y los **binarios de infraestructura** que sirven al agente (`fn_match`, `fn doctor`, `call_monitor`) **pueden leer `registry.db` directo** via `sqlite3` o `database/sql` con conexion read-only. NO estan sujetos a la regla MCP-first porque:
- No son acciones del agente — son inspeccion automatizada del entorno.
- El MCP requiere tool invocation por Claude; un hook no puede invocar tools.
- Latencia objetivo (50-200ms) incompatible con round-trip MCP.
**Restricciones:**
- SOLO lectura. Conexion debe abrirse con `?mode=ro` o `?_query_only=1`.
- NUNCA escritura a `registry.db` desde hooks.
- Si un hook necesita escribir (cache, telemetria propia), usa su propia DB (`operations.db` del app de hooks, o `~/.fn_hooks/cache.db`).
Esta excepcion es **explicita y acotada** — no aplica al agente, que sigue regido por la regla MCP-first.
### Verificacion previa — `fn doctor`
Antes de empezar trabajo no trivial sobre el registry, ejecutar `fn doctor` para confirmar que el ecosistema esta sano:
- Artefactos OK (sin `git_not_initialized`, `venv_broken_path`, etc.).
- Services activos cuando se necesiten (`sqlite_api`, `registry_api`, `registry_mcp`).
- Sin drift `pc_locations` vs disco.
- Sin drift `uses_functions` vs imports reales.
Si `fn doctor` reporta `service inactive` para `registry_mcp.service`, el MCP estara siendo invocado en modo stdio por Claude Code (normal); el systemd unit solo aplica al modo HTTP. Si el binario no responde, rebuild: `cd apps/registry_mcp && CGO_ENABLED=1 go build -tags fts5 -o registry_mcp .`.
### Tools MCP disponibles
| Tool | Lectura/escritura | Gating |
|---|---|---|
| `fn_search` | read | siempre on |
| `fn_show` | read | siempre on |
| `fn_code` | read | siempre on |
| `fn_uses` | read | siempre on |
| `fn_list_domains` | read | siempre on |
| `fn_proposal` | read | siempre on |
| `fn_doctor` | read | siempre on |
| `fn_run` | execute (mutating side-effects) | requiere `--enable-run` |
| `fn_create_function` | write | requiere `--enable-write` |
### Heredoc Python — convenciones obligatorias
Cuando el caso 3 (composicion) sea inevitable:
1. **Imports explicitos** desde paquetes del registry. Nunca `import *`.
2. **No reescribir** la firma de una funcion del registry — importarla.
3. **Args via env vars o stdin JSON**, nunca interpolacion shell directa (inyeccion).
4. **Output a stdout JSON** cuando vaya a ser consumido por el siguiente paso.
5. **Si el heredoc supera ~30 lineas**, extraer a `python/functions/pipelines/`. El monitor avisara automaticamente cuando un patron similar se repita >5 veces.
### Trazabilidad — bucle reactivo
Cada evento alimenta a `call_monitor.db` (event-log append-only) y se rollupea en una vista `function_stats` con contadores por funcion del registry. Tablas event-log:
| Tabla | Captura |
|---|---|
| `calls` | Cada invocacion (heredoc/mcp/fn_run): function_id, tool_used, duration_ms, success, error_class, args_hash |
| `code_writes` | Cada Edit/Write sobre archivo del registry: function_id, session_id, lines_added/removed |
| `test_runs` | Cada `go test`/`pytest` que toca codigo del registry: function_id, test_id, passed, duration_ms |
| `e2e_runs_fn` | Cada check `e2e_checks` de app que usa la funcion: function_id, app_id, check_id, passed |
| `violations` | Antipatron detectado: rule_id, session_id, command_snippet, severity |
| `patterns` | Heredocs clusterizados: pattern_hash, session_ids[], occurrences, representative_snippet |
| `sessions` | session_id, cwd, started_at, ended_at, health_score, mcp_ratio |
Vista agregada `function_stats` por `function_id`:
- **Uso:** `calls_total`, `calls_24h/7d/30d/90d`, `last_used_at`
- **Errores:** `errors_total`, `error_rate`, `last_error_class`, `last_error_ts`
- **Performance:** `mean_duration_ms`, `p95_duration_ms`
- **Codigo:** `writes_count`, `last_write_at`
- **Tests:** `tests_total`, `tests_failed`, `test_fail_rate`, `last_test_failed_at`
- **E2E:** `e2e_total`, `e2e_failed`, `e2e_fail_rate`, `consumer_apps_count`
- **Salud:** `violations_caused`
Assertions derivadas → proposals automaticas:
| Regla | Threshold | Proposal |
|---|---|---|
| Huerfana absoluta | `calls_90d=0 AND writes_count=0` | `deprecate_function` |
| Bug prioritario | `error_rate>0.1 AND calls_7d>5` | `improve_function` (bug) |
| Regresion performance | `p95_24h > 1.5 * p95_30d` | `improve_function` (perf) |
| Test flaky | `test_fail_rate>0.1 AND tests_total>10` | `improve_function` (flaky) |
| Wrapper saltado | `violations_caused>3` | `improve_function` (API gap) |
| Patron inline sin funcion | `patterns.occurrences>5 AND no match FTS` | `new_function` con snippet |
| Blast radius alto | `e2e_fail_rate>0 AND consumer_apps_count>=3` | `improve_function` (critical) |
Datos sensibles: solo `args_hash`, NUNCA valores concretos. Snippets de error redactados via allowlist.
### Capas de monitorizacion (issue 0085)
Cobertura por capa, no todas activas a la vez:
| # | Capa | Activacion | Cobertura |
|---|---|---|---|
| 1 | Hook PostToolUse Bash | siempre (settings.local.json) | mcp, fn_cli_run, edit_registry, violations |
| 2 | Wrapper Python `registry_telemetry` | `FN_TELEMETRY=1` env var | heredocs + notebooks Jupyter |
| 3 | Wrapper Bash `telemetry_prelude.sh` | `source` explicito o `FN_TELEMETRY=1` | heredoc bash + apps bash |
| 4 | Interceptor en `fn run` | siempre (binario Go) | duration/error real de invocacion CLI |
| 5 | `fn doctor copied-code` | comando manual / cron | drift estatico: codigo copiado en apps |
| 6 | `function_versions` + snapshot | poblado por `fn index` + edit-hook | historial de versiones |
| 7-8 | Build-tag Go / macro C++ | opt-in por app | runtime de app (futuro) |
**Boundary:** monitorizamos al **agente** y a **invocaciones canonicas**. Runtime de apps Go/C++ compiladas queda fuera. Compensar con tests + `e2e_checks` (issue 0068).
### Que NO se monitoriza
- Funcion Go/C++ llamada internamente por app ya compilada.
- Funcion ejecutada por systemd timer / cron / dag_engine **step `command:`** (no `function:`) sin pasar por `fn run`. Nota: dag_engine steps con `function:` SI quedan trazados — el executor invoca `fn run <id>` y guarda `function_id` en `dag_step_results`.
- Sub-agente (`Agent` tool) — sus tools no propagan a hook del padre.
- Service de produccion recibiendo HTTP.
**Implicacion:** una funcion con `calls_90d=0` puede ser huerfana real O usada en runtime invisible. Antes de proponer `deprecate_function`, cruzar con `consumer_apps_count > 0` (e2e) o con `fn doctor uses-functions` (declaraciones estaticas).
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env bash
# Append a one-liner [[fn_id]] — purpose to MEMORY.md after fn-constructor
# creates a new registry function. Idempotent: skips if id already present.
# Used by /fn_claude step 5b (issue 0087, pieza 6).
#
# Usage: append_fn_to_memory.sh <fn_id> "<one-line purpose>"
set -euo pipefail
FN_ID="${1:-}"
PURPOSE="${2:-}"
if [ -z "$FN_ID" ] || [ -z "$PURPOSE" ]; then
echo "usage: append_fn_to_memory.sh <fn_id> <purpose>" >&2
exit 2
fi
MEM_DIR="${CLAUDE_MEMORY_DIR:-/home/lucas/.claude/projects/-home-lucas-fn-registry/memory}"
MEM_FILE="$MEM_DIR/MEMORY.md"
[ -d "$MEM_DIR" ] || { echo "memory dir missing: $MEM_DIR" >&2; exit 1; }
[ -f "$MEM_FILE" ] || { echo "MEMORY.md missing: $MEM_FILE" >&2; exit 1; }
# Per-function reference file slug
SLUG="reference_fn_${FN_ID}.md"
REF_FILE="$MEM_DIR/$SLUG"
# Idempotency: if already linked in MEMORY.md, exit 0
if grep -qF "[fn-$FN_ID]" "$MEM_FILE" 2>/dev/null; then
echo "already in MEMORY.md: $FN_ID"
exit 0
fi
# 1. Create reference memory file
cat > "$REF_FILE" <<EOF
---
name: fn-$FN_ID
description: Registry function $FN_ID — $PURPOSE
metadata:
type: reference
---
Registry function: \`$FN_ID\`
$PURPOSE
Invoke via \`./fn run $FN_ID [args]\` or \`mcp__registry__fn_run id="$FN_ID"\`. Inspect with \`mcp__registry__fn_show id="$FN_ID"\` / \`mcp__registry__fn_code id="$FN_ID"\`.
EOF
# 2. Append index line to MEMORY.md
printf -- '- [%s](%s) — %s\n' "fn-$FN_ID" "$SLUG" "$PURPOSE" >> "$MEM_FILE"
echo "appended: $FN_ID -> $MEM_FILE"
+243
View File
@@ -0,0 +1,243 @@
#!/usr/bin/env bash
# PostToolUse hook: registra cada invocacion del agente en
# projects/fn_monitoring/apps/call_monitor/operations.db (issue 0085b).
#
# Identifica tool, extrae function_id cuando es posible, clasifica el patron
# (mcp_*, fn_cli_run, heredoc_py, sqlite_direct, edit_registry, ...) y
# detecta antipatrones para registrar violations.
#
# NUNCA bloquea la herramienta. Falla silenciosamente si la BD no esta lista.
# Solo guarda args_hash, jamas valores concretos.
set -euo pipefail
# ---- Resolve registry root (walks up from cwd looking for registry.db) ----
resolve_root() {
local d="${PWD}"
while [ "$d" != "/" ]; do
if [ -f "$d/registry.db" ]; then
printf '%s' "$d"
return 0
fi
d=$(dirname "$d")
done
return 1
}
ROOT=$(resolve_root) || exit 0
DB="$ROOT/projects/fn_monitoring/apps/call_monitor/operations.db"
# Si la BD aun no existe, el hook no hace nada (esperando init).
[ -f "$DB" ] || exit 0
# ---- Read stdin JSON ----
INPUT=$(cat)
if [ -z "$INPUT" ]; then exit 0; fi
# Required jq presence
command -v jq >/dev/null 2>&1 || exit 0
command -v sqlite3 >/dev/null 2>&1 || exit 0
TOOL_NAME=$(printf '%s' "$INPUT" | jq -r '.tool_name // ""')
SESSION_ID=$(printf '%s' "$INPUT" | jq -r '.session_id // ""')
TS=$(date -u +%s)
# Tool response success/error
SUCCESS=1
ERROR_CLASS=""
ERROR_SNIPPET=""
RESP_IS_ERROR=$(printf '%s' "$INPUT" | jq -r 'if (.tool_response | type) == "object" then (.tool_response.is_error // false) else false end')
if [ "$RESP_IS_ERROR" = "true" ]; then
SUCCESS=0
ERROR_SNIPPET=$(printf '%s' "$INPUT" | jq -r 'if (.tool_response | type) == "object" then (.tool_response.error // .tool_response.content // "") else "" end' | head -c 240 | tr '\n' ' ')
fi
# args_hash: sha256 truncado del tool_input (sin valores)
ARGS_HASH=$(printf '%s' "$INPUT" | jq -c '.tool_input // {}' | sha256sum | cut -c1-16)
# Helpers SQL
sql_escape() { printf '%s' "$1" | sed "s/'/''/g"; }
insert_call() {
local fn_id="$1" tool_used="$2" duration_ms="${3:-0}" snippet="${4:-}"
local fn_esc tu_esc ec_esc es_esc sid_esc ah_esc snip_esc
# Politica issue 0087: command_snippet solo se rellena cuando function_id
# esta vacio. Si la call golpea una funcion del registry, su ID y
# tool_used bastan; no duplicamos el comando.
if [ -n "$fn_id" ]; then snippet=""; fi
# Redact common secrets antes de persistir
snippet=$(printf '%s' "$snippet" \
| sed -E 's/(password|token|secret|api[_-]?key|bearer)([[:space:]]*[=:][[:space:]]*)[^[:space:]]+/\1\2<REDACTED>/Ig' \
| head -c 200)
fn_esc=$(sql_escape "$fn_id")
tu_esc=$(sql_escape "$tool_used")
ec_esc=$(sql_escape "$ERROR_CLASS")
es_esc=$(sql_escape "$ERROR_SNIPPET")
sid_esc=$(sql_escape "$SESSION_ID")
ah_esc=$(sql_escape "$ARGS_HASH")
snip_esc=$(sql_escape "$snippet")
sqlite3 "$DB" "INSERT INTO calls (session_id, function_id, tool_used, args_hash, duration_ms, success, error_class, error_snippet, command_snippet, ts) VALUES ('$sid_esc','$fn_esc','$tu_esc','$ah_esc',$duration_ms,$SUCCESS,'$ec_esc','$es_esc','$snip_esc',$TS);" 2>/dev/null || true
}
insert_code_write() {
local fn_id="$1" file_path="$2" added="${3:-0}" removed="${4:-0}"
local fn_esc fp_esc sid_esc
fn_esc=$(sql_escape "$fn_id")
fp_esc=$(sql_escape "$file_path")
sid_esc=$(sql_escape "$SESSION_ID")
sqlite3 "$DB" "INSERT INTO code_writes (session_id, function_id, file_path, lines_added, lines_removed, ts) VALUES ('$sid_esc','$fn_esc','$fp_esc',$added,$removed,$TS);" 2>/dev/null || true
}
# Snapshot a function version row when an edit lands on a registry file.
# Uses sha256 of file bytes as content_hash (separate namespace from index source).
insert_edit_version() {
local fn_id="$1" abs_path="$2"
[ -f "$abs_path" ] || return 0
command -v sha256sum >/dev/null 2>&1 || return 0
local hash
hash=$(sha256sum "$abs_path" 2>/dev/null | awk '{print $1}')
[ -z "$hash" ] && return 0
local fn_esc h_esc
fn_esc=$(sql_escape "$fn_id")
h_esc=$(sql_escape "$hash")
sqlite3 "$DB" "INSERT OR IGNORE INTO function_versions (function_id, content_hash, version, snapped_at, source, lines_added, lines_removed) VALUES ('$fn_esc','$h_esc','',$TS,'edit_hook',0,0);" 2>/dev/null || true
}
insert_violation() {
local rule_id="$1" fn_id="$2" snippet="$3" severity="${4:-warning}"
local r_esc fn_esc sn_esc sev_esc sid_esc
r_esc=$(sql_escape "$rule_id")
fn_esc=$(sql_escape "$fn_id")
sn_esc=$(sql_escape "$(printf '%s' "$snippet" | head -c 240 | tr '\n' ' ')")
sev_esc=$(sql_escape "$severity")
sid_esc=$(sql_escape "$SESSION_ID")
sqlite3 "$DB" "INSERT INTO violations (session_id, rule_id, function_id, command_snippet, severity, ts) VALUES ('$sid_esc','$r_esc','$fn_esc','$sn_esc','$sev_esc',$TS);" 2>/dev/null || true
}
# ---- Derive function_id from registry file path ----
# Matches paths under functions/<domain>/<name>.<ext>, python/functions/<domain>/<name>.py,
# bash/functions/<domain>/<name>.sh, frontend/functions/<domain>/<name>.ts(x)
derive_fn_id_from_path() {
local p="$1"
[ -z "$p" ] && return 1
case "$p" in
functions/*/*.go|*/functions/*/*.go)
local dom name
dom=$(printf '%s' "$p" | sed -E 's|.*functions/([^/]+)/.*|\1|')
name=$(printf '%s' "$p" | sed -E 's|.*functions/[^/]+/([^/.]+)\..*|\1|')
[ -n "$dom" ] && [ -n "$name" ] && printf '%s_go_%s' "$name" "$dom" && return 0 ;;
python/functions/*/*.py)
local dom name
dom=$(printf '%s' "$p" | sed -E 's|python/functions/([^/]+)/.*|\1|')
name=$(printf '%s' "$p" | sed -E 's|python/functions/[^/]+/([^/.]+)\..*|\1|')
[ -n "$dom" ] && [ -n "$name" ] && printf '%s_py_%s' "$name" "$dom" && return 0 ;;
bash/functions/*/*.sh)
local dom name
dom=$(printf '%s' "$p" | sed -E 's|bash/functions/([^/]+)/.*|\1|')
name=$(printf '%s' "$p" | sed -E 's|bash/functions/[^/]+/([^/.]+)\..*|\1|')
[ -n "$dom" ] && [ -n "$name" ] && printf '%s_bash_%s' "$name" "$dom" && return 0 ;;
frontend/functions/*/*.ts|frontend/functions/*/*.tsx)
local dom name
dom=$(printf '%s' "$p" | sed -E 's|frontend/functions/([^/]+)/.*|\1|')
name=$(printf '%s' "$p" | sed -E 's|frontend/functions/[^/]+/([^/.]+)\..*|\1|')
[ -n "$dom" ] && [ -n "$name" ] && printf '%s_ts_%s' "$name" "$dom" && return 0 ;;
esac
return 1
}
# ---- Dispatch by tool ----
case "$TOOL_NAME" in
mcp__registry__fn_search)
insert_call "" "mcp_fn_search"
;;
mcp__registry__fn_show)
ID=$(printf '%s' "$INPUT" | jq -r '.tool_input.id // ""')
insert_call "$ID" "mcp_fn_show"
;;
mcp__registry__fn_code)
ID=$(printf '%s' "$INPUT" | jq -r '.tool_input.id // ""')
insert_call "$ID" "mcp_fn_code"
;;
mcp__registry__fn_uses)
ID=$(printf '%s' "$INPUT" | jq -r '.tool_input.id // ""')
insert_call "$ID" "mcp_fn_uses"
;;
mcp__registry__fn_run)
ID=$(printf '%s' "$INPUT" | jq -r '.tool_input.id // ""')
insert_call "$ID" "mcp_fn_run"
;;
mcp__registry__fn_list_domains)
insert_call "" "mcp_fn_list_domains"
;;
mcp__registry__fn_proposal)
insert_call "" "mcp_fn_proposal"
;;
mcp__registry__fn_doctor)
insert_call "" "mcp_fn_doctor"
;;
mcp__registry__fn_create_function)
insert_call "" "mcp_fn_create_function"
;;
Edit|Write|MultiEdit)
FILE_PATH=$(printf '%s' "$INPUT" | jq -r '.tool_input.file_path // ""')
ABS_PATH="$FILE_PATH"
# Make path relative to root if absolute and inside root
case "$FILE_PATH" in
"$ROOT"/*) FILE_PATH="${FILE_PATH#$ROOT/}" ;;
/*) ABS_PATH="$FILE_PATH" ;;
*) ABS_PATH="$ROOT/$FILE_PATH" ;;
esac
FN_ID=$(derive_fn_id_from_path "$FILE_PATH" || true)
if [ -n "$FN_ID" ]; then
insert_code_write "$FN_ID" "$FILE_PATH" 0 0
insert_call "$FN_ID" "edit_registry"
insert_edit_version "$FN_ID" "$ABS_PATH"
fi
;;
Bash)
CMD=$(printf '%s' "$INPUT" | jq -r '.tool_input.command // ""')
CMD_HEAD=$(printf '%s' "$CMD" | head -c 200 | tr '\n' ' ')
# Classify
TOOL_USED="bash_other"
FN_ID=""
if printf '%s' "$CMD" | grep -qE '(^|[[:space:]])\./fn[[:space:]]+run[[:space:]]+'; then
TOOL_USED="fn_cli_run"
FN_ID=$(printf '%s' "$CMD" | sed -nE 's/.*\.\/fn[[:space:]]+run[[:space:]]+([A-Za-z0-9_]+).*/\1/p' | head -n1)
elif printf '%s' "$CMD" | grep -qE 'python/\.venv/bin/python3[[:space:]]+-[[:space:]]+<<'; then
TOOL_USED="heredoc_py"
elif printf '%s' "$CMD" | grep -qE 'sqlite3[[:space:]][^|]*\bregistry\.db\b'; then
TOOL_USED="sqlite_direct"
fi
insert_call "$FN_ID" "$TOOL_USED" 0 "$CMD_HEAD"
# ---- Violation rules ----
# 1. sqlite3 directo SELECT sobre registry.db (excepto schema/pragma/count/join)
if [ "$TOOL_USED" = "sqlite_direct" ]; then
if ! printf '%s' "$CMD" | grep -qiE '(\.schema|\.tables|PRAGMA[[:space:]]+(table_info|index_list)|COUNT\(|GROUP[[:space:]]+BY|JOIN[[:space:]])'; then
insert_violation "sqlite3_registry_select" "" "$CMD_HEAD" "warning"
fi
fi
# 2. python -c "import X; dir(X)"
if printf '%s' "$CMD" | grep -qE 'python[3]?[[:space:]]+-c[[:space:]]+["'\''].*import.*(dir|help)\('; then
insert_violation "python_dir_inspect" "" "$CMD_HEAD" "info"
fi
# 3. from <pkg> import * (en heredoc python)
if [ "$TOOL_USED" = "heredoc_py" ]; then
if printf '%s' "$CMD" | grep -qE 'from[[:space:]]+[A-Za-z0-9_.]+[[:space:]]+import[[:space:]]+\*'; then
insert_violation "import_star_in_heredoc" "" "$CMD_HEAD" "warning"
fi
if printf '%s' "$CMD" | grep -qE 'client\._http\.request\('; then
insert_violation "client_http_request_direct" "" "$CMD_HEAD" "warning"
fi
fi
;;
esac
exit 0
+121
View File
@@ -0,0 +1,121 @@
#!/usr/bin/env bash
# UserPromptSubmit hook: inyecta capacidades calientes (TOP/FRESH/PIPELINES)
# del registry como additionalContext en cada turno del usuario.
#
# Cache: ~/.cache/fn_registry/capabilities.txt (TTL 1h).
# Fuente: `./fn doctor capabilities --emit-claude-md` desde la raiz del repo.
#
# NUNCA bloquea: si algo falla, emite contexto vacio y sale 0.
set -uo pipefail
CACHE_DIR="${HOME}/.cache/fn_registry"
CACHE_FILE="${CACHE_DIR}/capabilities.txt"
TTL_SECONDS=3600
# Resolve registry root (walks up from cwd, fallback CLAUDE_PROJECT_DIR)
resolve_root() {
local d="${PWD}"
while [ "$d" != "/" ]; do
if [ -f "$d/registry.db" ] && [ -x "$d/fn" ]; then
printf '%s' "$d"
return 0
fi
d=$(dirname "$d")
done
if [ -n "${CLAUDE_PROJECT_DIR:-}" ] && [ -f "${CLAUDE_PROJECT_DIR}/registry.db" ]; then
printf '%s' "${CLAUDE_PROJECT_DIR}"
return 0
fi
return 1
}
# Consume stdin (UserPromptSubmit payload) — we don't need it but keep stdin clean
cat >/dev/null 2>&1 || true
ROOT=$(resolve_root) || exit 0
mkdir -p "$CACHE_DIR" 2>/dev/null || exit 0
# Cache freshness check
need_refresh=1
if [ -f "$CACHE_FILE" ]; then
now=$(date +%s)
mtime=$(stat -c %Y "$CACHE_FILE" 2>/dev/null || stat -f %m "$CACHE_FILE" 2>/dev/null || echo 0)
age=$((now - mtime))
if [ "$age" -lt "$TTL_SECONDS" ]; then
need_refresh=0
fi
fi
if [ "$need_refresh" -eq 1 ]; then
# Regenerate: call fn doctor capabilities --emit-claude-md and process
raw=$("$ROOT/fn" doctor capabilities --emit-claude-md 2>/dev/null || true)
if [ -z "$raw" ]; then
exit 0
fi
# Extract top 5 from each section using awk.
# Sections detected by "## ... Top" / "## ... Fresh" / "## ... Pipelines".
line=$(printf '%s\n' "$raw" | awk '
BEGIN { sec=""; n_top=0; n_fresh=0; n_pipe=0; }
/^## .*Top 20/ { sec="TOP"; next }
/^## .*Fresh/ { sec="FRESH"; next }
/^## .*Pipelines/ { sec="PIPE"; next }
/^## / { sec=""; next }
/^- `/ {
# extract first backticked token
s = $0
sub(/^- `/, "", s)
i = index(s, "`")
if (i == 0) next
id = substr(s, 1, i-1)
if (sec == "TOP" && n_top < 5) { tops[n_top++] = id }
if (sec == "FRESH" && n_fresh < 5) { fresh[n_fresh++] = id }
if (sec == "PIPE" && n_pipe < 5) { pipes[n_pipe++] = id }
}
END {
out = "CAPABILITIES (cache 1h):"
if (n_top > 0) {
line = " TOP: " tops[0]
for (i=1; i<n_top; i++) line = line ", " tops[i]
out = out "\n" line
}
if (n_fresh > 0) {
line = " FRESH (7d): " fresh[0]
for (i=1; i<n_fresh; i++) line = line ", " fresh[i]
out = out "\n" line
}
if (n_pipe > 0) {
line = " PIPELINES: " pipes[0]
for (i=1; i<n_pipe; i++) line = line ", " pipes[i]
out = out "\n" line
}
print out
}
')
if [ -z "$line" ]; then
exit 0
fi
printf '%s\n' "$line" >"$CACHE_FILE" 2>/dev/null || exit 0
fi
# Emit cached content as additionalContext
if [ ! -s "$CACHE_FILE" ]; then
exit 0
fi
ctx=$(cat "$CACHE_FILE")
if command -v jq >/dev/null 2>&1; then
jq -n --arg ctx "$ctx" '{
hookSpecificOutput: {
hookEventName: "UserPromptSubmit",
additionalContext: $ctx
}
}'
else
# Fallback: print raw text (Claude Code prints stdout as context too)
printf '%s\n' "$ctx"
fi
exit 0
+107
View File
@@ -0,0 +1,107 @@
#!/usr/bin/env bash
# PostToolUse hook: gate "tag de capability group obligatorio" tras crear/modificar
# funciones del registry. Issue 0086 paso 9/gate.
#
# Comportamiento:
# - Detecta .md de funciones (functions/, python/functions/, bash/functions/,
# frontend/functions/, cpp/functions/) modificados en los ultimos 60s.
# - Lee frontmatter `tags:` y verifica si al menos uno coincide con un capability
# group declarado en docs/capabilities/INDEX.md.
# - Si NO hay match -> emite additionalContext con la lista de funciones afectadas.
# - NUNCA bloquea. Solo warning visible.
#
# Salida JSON consumida por Claude Code:
# { "hookSpecificOutput": { "hookEventName": "PostToolUse",
# "additionalContext": "..." } }
set -euo pipefail
resolve_root() {
local d="${PWD}"
while [ "$d" != "/" ]; do
if [ -f "$d/registry.db" ]; then
printf '%s' "$d"
return 0
fi
d=$(dirname "$d")
done
return 1
}
ROOT=$(resolve_root) || exit 0
INDEX="$ROOT/docs/capabilities/INDEX.md"
# Si no existe el INDEX aun, no hay grupos definidos -> nada que verificar.
[ -f "$INDEX" ] || exit 0
# Consume stdin (sin parsear — no necesitamos session_id para este gate)
cat >/dev/null
# Solo correr si hay jq disponible
command -v jq >/dev/null 2>&1 || exit 0
# 1. Cargar lista de capability groups desde el INDEX.
# Formato esperado en INDEX.md: | [name](name.md) | N | descripcion |
CAP_GROUPS=$(grep -oE '\[[a-z][a-z0-9_-]*\]\([a-z][a-z0-9_-]*\.md\)' "$INDEX" \
| sed -E 's/^\[([^]]+)\].*/\1/' \
| sort -u)
[ -z "$CAP_GROUPS" ] && exit 0
# 2. Encontrar .md de funciones modificados en ultimos 60s.
RECENT=$(find "$ROOT/functions" "$ROOT/python/functions" "$ROOT/bash/functions" \
"$ROOT/frontend/functions" "$ROOT/cpp/functions" \
-maxdepth 4 -type f -name '*.md' -mmin -1 2>/dev/null || true)
[ -z "$RECENT" ] && exit 0
# 3. Para cada .md reciente: extraer tags del frontmatter, comparar con groups.
MISSING=""
while IFS= read -r mdfile; do
[ -z "$mdfile" ] && continue
# Extrae el bloque entre los dos `---` del inicio
front=$(awk '/^---$/{c++; next} c==1 {print} c>=2 {exit}' "$mdfile" 2>/dev/null || true)
[ -z "$front" ] && continue
# tags: [a, b, c] o tags:\n - a\n - b
tags_inline=$( { printf '%s\n' "$front" | grep -E '^tags:[[:space:]]*\[' | head -1 \
| sed -E 's/^tags:[[:space:]]*\[(.*)\].*$/\1/' \
| tr ',' '\n' | sed -E 's/^[[:space:]"]+|[[:space:]"]+$//g'; } || true )
tags_block=$( { printf '%s\n' "$front" | awk '
/^tags:[[:space:]]*$/ {intag=1; next}
intag && /^[[:space:]]*-[[:space:]]/ {sub(/^[[:space:]]*-[[:space:]]*/, ""); print; next}
intag && !/^[[:space:]]/ {intag=0}
' | sed -E 's/^[[:space:]"]+|[[:space:]"]+$//g'; } || true )
tags=$( { printf '%s\n%s\n' "$tags_inline" "$tags_block" | grep -v '^$'; } || true )
matched=0
while IFS= read -r g; do
[ -z "$g" ] && continue
if printf '%s\n' "$tags" | grep -qx "$g"; then
matched=1
break
fi
done <<< "$CAP_GROUPS"
if [ "$matched" -eq 0 ]; then
rel="${mdfile#$ROOT/}"
MISSING="${MISSING}${rel}\n"
fi
done <<< "$RECENT"
# 4. Si hay funciones sin tag de grupo, emitir aviso.
if [ -n "$MISSING" ]; then
CAP_GROUPS_CSV=$(printf '%s' "$CAP_GROUPS" | tr '\n' ',' | sed 's/,$//')
WARN="CAPABILITY-GAP (issue 0086): funcion(es) recien tocada(s) sin tag de capability group: $(printf '%b' "$MISSING" | tr '\n' ' ')"
WARN+="| Grupos disponibles: ${CAP_GROUPS_CSV}. Anade al menos uno al frontmatter \`tags:\` y corre \`./fn index\`. Si la funcion no encaja en ningun grupo existente, considera crear grupo nuevo (>=3 funciones) o dejarla con tag plano (no de grupo)."
jq -n --arg ctx "$WARN" '{
hookSpecificOutput: {
hookEventName: "PostToolUse",
additionalContext: $ctx
}
}'
fi
exit 0
+133
View File
@@ -0,0 +1,133 @@
#!/usr/bin/env bash
# PreToolUse hook: sugiere funciones del registry cuando un comando Bash
# inline probablemente reinventa una funcion existente (issue 0087).
#
# Llama a `./fn match "<cmd>"` con timeout 200ms. Si encaja con alta
# confianza, imprime un <system-reminder> a stderr para que Claude Code
# lo lea como recordatorio. NUNCA bloquea la tool — exit 0 siempre.
set -euo pipefail
# ---- Always exit 0, no matter what ----
trap 'exit 0' ERR
# ---- Resolve registry root (walks up from cwd) ----
resolve_root() {
local d="${PWD}"
while [ "$d" != "/" ]; do
if [ -f "$d/registry.db" ]; then
printf '%s' "$d"
return 0
fi
d=$(dirname "$d")
done
return 1
}
ROOT=$(resolve_root) || exit 0
FN_BIN="$ROOT/fn"
[ -x "$FN_BIN" ] || exit 0
# ---- Read stdin JSON ----
command -v jq >/dev/null 2>&1 || exit 0
INPUT=$(cat)
[ -z "$INPUT" ] && exit 0
TOOL_NAME=$(printf '%s' "$INPUT" | jq -r '.tool_name // ""' 2>/dev/null || echo "")
[ "$TOOL_NAME" = "Bash" ] || exit 0
CMD=$(printf '%s' "$INPUT" | jq -r '.tool_input.command // ""' 2>/dev/null || echo "")
[ -z "$CMD" ] && exit 0
# Single-line for matching against denylist patterns
CMD_FLAT=$(printf '%s' "$CMD" | tr '\n' ' ')
# ---- Denylist (skip antes de llamar fn match para ahorrar el invoke) ----
# Comandos demasiado cortos -> trivial
CMD_LEN=${#CMD_FLAT}
[ "$CMD_LEN" -lt 20 ] && exit 0
# Trivial single-utility commands
case "$CMD_FLAT" in
"ls"|"ls "*|"cd"|"cd "*|"pwd"|"pwd "*|"cat"|"cat "*|"echo"|"echo "*)
exit 0 ;;
"grep"|"grep "*|"head"|"head "*|"tail"|"tail "*|"wc"|"wc "*)
exit 0 ;;
"mkdir"|"mkdir "*|"rm"|"rm "*|"mv"|"mv "*|"cp"|"cp "*)
exit 0 ;;
"git"|"git "*)
exit 0 ;;
"go"|"go "*)
# go build / go test corrientes — el agente ya los maneja
exit 0 ;;
esac
# Comandos que ya usan el registry: ./fn ..., fn run ..., mcp__registry__*
if printf '%s' "$CMD_FLAT" | grep -qE '(^|[[:space:]])\./fn([[:space:]]|$)'; then
exit 0
fi
if printf '%s' "$CMD_FLAT" | grep -qE '(^|[[:space:]])fn[[:space:]]+(run|search|show|code|uses|doctor|index|match|list|add|proposal|sync|ops|check)'; then
exit 0
fi
# Pure-cd (movement only, no logic)
if printf '%s' "$CMD_FLAT" | grep -qE '^[[:space:]]*cd[[:space:]]+[^&|;]+$'; then
exit 0
fi
# ---- Llamar fn match con timeout 200ms ----
command -v timeout >/dev/null 2>&1 || exit 0
# Truncar el comando a algo razonable para fn match (evitar args huge)
CMD_TRUNC=$(printf '%s' "$CMD_FLAT" | head -c 500)
MATCH_JSON=$(timeout 0.2 "$FN_BIN" match "$CMD_TRUNC" --format json --top 3 2>/dev/null) || exit 0
[ -z "$MATCH_JSON" ] && exit 0
# ---- Parsear JSON ----
HIGH_CONF=$(printf '%s' "$MATCH_JSON" | jq -r '.high_confidence // false' 2>/dev/null || echo "false")
TOP_ID=$(printf '%s' "$MATCH_JSON" | jq -r '.top[0].id // ""' 2>/dev/null || echo "")
TOP_SCORE=$(printf '%s' "$MATCH_JSON" | jq -r '.top[0].score // 0' 2>/dev/null || echo "0")
TOP_SIG=$(printf '%s' "$MATCH_JSON" | jq -r '.top[0].signature // ""' 2>/dev/null || echo "")
TOP_SNIP=$(printf '%s' "$MATCH_JSON" | jq -r '.top[0].snippet // ""' 2>/dev/null || echo "")
[ -z "$TOP_ID" ] && exit 0
# Trigger condition: (high_confidence==true OR score>=0.85) AND score>=0.6
# - high_confidence requires top1/top2 gap > 1.5 (set por fn match)
# - score>=0.85 cubre matches muy fuertes donde el gap es modesto
SCORE_HI=$(awk -v s="$TOP_SCORE" 'BEGIN{ print (s+0 >= 0.85) ? "1" : "0" }')
SCORE_MIN=$(awk -v s="$TOP_SCORE" 'BEGIN{ print (s+0 >= 0.6) ? "1" : "0" }')
[ "$SCORE_MIN" = "1" ] || exit 0
if [ "$HIGH_CONF" != "true" ] && [ "$SCORE_HI" != "1" ]; then
exit 0
fi
# Truncar snippet a 100 chars y limpiar saltos de linea
SNIP_SHORT=$(printf '%s' "$TOP_SNIP" | tr '\n' ' ' | head -c 100)
# Formatear score con 2 decimales
SCORE_FMT=$(awk -v s="$TOP_SCORE" 'BEGIN{ printf "%.2f", s+0 }')
# ---- Emitir <system-reminder> a stderr ----
cat >&2 <<EOF
<system-reminder>FUZZY-MATCH (issue 0087): your Bash command may already be a function.
USE: ./fn run $TOP_ID -> $TOP_SIG
SNIPPET: $SNIP_SHORT
Confidence: $SCORE_FMT. If you proceed inline, the violation will be logged.
</system-reminder>
EOF
exit 0
# Test manual:
# echo '{"tool_name":"Bash","tool_input":{"command":"taskkill.exe /IM registry_dashboard.exe /F"},"session_id":"test"}' \
# | bash .claude/scripts/hook_fn_match.sh
#
# Casos silenciosos:
# echo '{"tool_name":"Bash","tool_input":{"command":"ls -la"},"session_id":"test"}' \
# | bash .claude/scripts/hook_fn_match.sh
# echo '{"tool_name":"Bash","tool_input":{"command":"./fn run filter_slice_go_core 1 2 3"},"session_id":"test"}' \
# | bash .claude/scripts/hook_fn_match.sh
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env bash
# UserPromptSubmit hook: recordatorio compacto de patrones canonicos del registry.
# Inyectado como additionalContext en cada turno del usuario.
# Issue 0085 (hardening 2).
#
# NUNCA bloquea. Solo printf de additionalContext.
set -euo pipefail
# Resolve registry root (walks up from cwd)
resolve_root() {
local d="${PWD}"
while [ "$d" != "/" ]; do
if [ -f "$d/registry.db" ]; then
printf '%s' "$d"
return 0
fi
d=$(dirname "$d")
done
return 1
}
ROOT=$(resolve_root) || exit 0
# Read input, extract session_id (UserPromptSubmit payload includes it)
INPUT=$(cat)
SESSION_ID=""
if command -v jq >/dev/null 2>&1; then
SESSION_ID=$(printf '%s' "$INPUT" | jq -r '.session_id // ""' 2>/dev/null || true)
fi
# Count current pending proposals + recent violations for situational awareness
PROPOSALS_PENDING="?"
VIOLATIONS_24H="?"
CALLS_24H="?"
CAP_CREATED=0
CAP_USED=0
CAP_ORPHAN=0
if command -v sqlite3 >/dev/null 2>&1; then
REG="$ROOT/registry.db"
MON="$ROOT/projects/fn_monitoring/apps/call_monitor/operations.db"
[ -f "$REG" ] && PROPOSALS_PENDING=$(sqlite3 "$REG" "SELECT COUNT(*) FROM proposals WHERE status='pending'" 2>/dev/null || echo "?")
if [ -f "$MON" ]; then
VIOLATIONS_24H=$(sqlite3 "$MON" "SELECT COUNT(*) FROM violations WHERE ts >= CAST(strftime('%s','now','-1 day') AS INTEGER)" 2>/dev/null || echo "?")
CALLS_24H=$(sqlite3 "$MON" "SELECT COUNT(*) FROM calls WHERE ts >= CAST(strftime('%s','now','-1 day') AS INTEGER)" 2>/dev/null || echo "?")
if [ -n "$SESSION_ID" ]; then
sid_esc=$(printf '%s' "$SESSION_ID" | sed "s/'/''/g")
CAP_CREATED=$(sqlite3 "$MON" "SELECT COUNT(*) FROM session_capability_growth WHERE session_id='$sid_esc'" 2>/dev/null || echo 0)
CAP_USED=$(sqlite3 "$MON" "SELECT COUNT(*) FROM session_capability_growth WHERE session_id='$sid_esc' AND calls_in_session>0" 2>/dev/null || echo 0)
CAP_ORPHAN=$(sqlite3 "$MON" "SELECT COUNT(*) FROM session_capability_growth WHERE session_id='$sid_esc' AND calls_in_session=0" 2>/dev/null || echo 0)
fi
fi
fi
REMINDER="REGISTRY-FIRST (issue 0085 telemetry active): "
REMINDER+="Inspect → mcp__registry__fn_search/show/code/uses/proposal. "
REMINDER+="Execute one fn → mcp__registry__fn_run or ./fn run. "
REMINDER+="Compose multi-fn → heredoc python IMPORTANDO del registry. "
REMINDER+="NUNCA sqlite3 registry.db directo (salvo schema/PRAGMA/COUNT/JOIN). "
REMINDER+="NUNCA reescribir inline logica que ya es funcion. "
REMINDER+="Si patron se repite >2x → propose nueva funcion via fn-constructor. "
REMINDER+="Estado: pending_proposals=${PROPOSALS_PENDING} violations_24h=${VIOLATIONS_24H} calls_24h=${CALLS_24H}. "
REMINDER+="CAPABILITY-GROWTH (issue 0086): created_this_session=${CAP_CREATED} used=${CAP_USED} orphan=${CAP_ORPHAN}. Si orphan>0 -> integra la funcion en el codigo o documenta por que se quedo huerfana. "
REMINDER+="Comando autocheck: /fn_claude."
jq -n --arg ctx "$REMINDER" '{
hookSpecificOutput: {
hookEventName: "UserPromptSubmit",
additionalContext: $ctx
}
}'
@@ -0,0 +1,121 @@
#!/bin/bash
# integrate-worktrees.sh — Integra branches de worktrees a master con --no-ff
#
# Uso: ./integrate-worktrees.sh <slug-1> <slug-2> ...
# Ejemplo: ./integrate-worktrees.sh 0026-split-runtime 0027-prune-config-schema
#
# Para cada slug:
# 1. git merge --no-ff issue/<slug> a master
# 2. Verificar que master compila después del merge
# 3. Si hay conflict o fallo de build, PARAR inmediatamente
#
# Los slugs deben pasarse en el orden correcto (waves ya resueltas).
# NO hace push — eso lo decide el usuario.
set -euo pipefail
REPO_ROOT="$(git rev-parse --show-toplevel)"
if [ $# -eq 0 ]; then
echo "ERROR: se necesita al menos un slug"
echo "Uso: $0 <slug-1> <slug-2> ..."
exit 1
fi
# Asegurar que estamos en master
echo "=== Cambiando a master ==="
cd "$REPO_ROOT"
git checkout master
MERGED=0
FAILED_AT=""
for slug in "$@"; do
branch="issue/${slug}"
echo ""
echo "=== Integrando: ${branch} ==="
# Verificar que la branch existe
if ! git show-ref --verify --quiet "refs/heads/${branch}"; then
echo "FAIL: branch ${branch} no existe"
FAILED_AT="$slug"
break
fi
# Merge --no-ff
if ! git merge --no-ff "$branch" -m "merge: ${branch} — implementación paralela"; then
echo ""
echo "CONFLICT: merge de ${branch} tiene conflictos"
echo "Resolver manualmente y luego continuar con los slugs restantes"
echo ""
echo "Para resolver:"
echo " 1. git status (ver archivos en conflicto)"
echo " 2. Resolver conflictos en cada archivo"
echo " 3. git add <archivos>"
echo " 4. git commit"
echo ""
echo "Slugs pendientes después de ${slug}:"
FOUND=0
for remaining in "$@"; do
if [ "$FOUND" -eq 1 ]; then
echo " - ${remaining}"
fi
if [ "$remaining" = "$slug" ]; then
FOUND=1
fi
done
exit 1
fi
echo "MERGED: ${branch}"
# Verificar que master sigue compilando (si BUILD_CMD esta definido)
if [ -n "${BUILD_CMD:-}" ]; then
echo "--- Verificando build post-merge ($BUILD_CMD) ---"
if ! (cd "$REPO_ROOT" && bash -c "$BUILD_CMD" 2>&1); then
echo ""
echo "FAIL: master no compila despues de mergear ${branch}"
echo "Revertir con: git reset --hard HEAD~1"
echo "Investigar el problema antes de continuar."
FAILED_AT="$slug"
break
fi
echo "OK: build post-merge exitoso"
else
echo "--- Build post-merge SKIPPED (BUILD_CMD no definido) ---"
fi
MERGED=$((MERGED + 1))
done
echo ""
echo "=== Resumen de integración ==="
echo "Mergeados: ${MERGED} de $#"
if [ -n "$FAILED_AT" ]; then
echo "Falló en: ${FAILED_AT}"
echo ""
echo "Worktrees NO limpiados (resolver primero el fallo)"
exit 1
fi
# Limpieza de worktrees y branches
echo ""
echo "=== Limpieza ==="
for slug in "$@"; do
path="${REPO_ROOT}/worktrees/${slug}"
branch="issue/${slug}"
if [ -d "$path" ]; then
git worktree remove "$path" 2>/dev/null && echo "REMOVED: worktree ${path}" || echo "WARN: no se pudo eliminar worktree ${path}"
fi
git branch -d "$branch" 2>/dev/null && echo "DELETED: branch ${branch}" || echo "WARN: no se pudo eliminar branch ${branch}"
done
echo ""
echo "=== Integración completa ==="
echo "Master tiene ${MERGED} merges nuevos."
echo ""
echo "Para publicar: git push"
@@ -0,0 +1,74 @@
#!/bin/bash
# setup-worktrees.sh — Crea git worktrees para ejecución paralela de issues
#
# Uso: ./setup-worktrees.sh <slug-1> <slug-2> ...
# Ejemplo: ./setup-worktrees.sh 0026-split-runtime 0027-prune-config-schema
#
# Cada slug genera:
# worktrees/<slug>/ (worktree completo)
# branch: issue/<slug>
set -euo pipefail
REPO_ROOT="$(git rev-parse --show-toplevel)"
WORKTREE_DIR="${REPO_ROOT}/worktrees"
if [ $# -eq 0 ]; then
echo "ERROR: se necesita al menos un slug de issue"
echo "Uso: $0 <slug-1> <slug-2> ..."
exit 1
fi
# Verificar master (NO pull --rebase: rompe merges locales convirtiendolos
# en cherry-picks contra origin/master viejo). Detectado 2026-05-18.
echo "=== Verificando master ==="
CURRENT_BRANCH="$(git branch --show-current)"
if [ "$CURRENT_BRANCH" != "master" ] && [ -n "$CURRENT_BRANCH" ]; then
echo "WARN: estas en branch '${CURRENT_BRANCH}', no master. Worktrees nuevos saldran de master ref de todos modos."
fi
# NO auto-pull. Usuario decide sync con remote.
mkdir -p "$WORKTREE_DIR"
CREATED=0
SKIPPED=0
FAILED=0
for slug in "$@"; do
branch="issue/${slug}"
path="${WORKTREE_DIR}/${slug}"
if [ -d "$path" ]; then
echo "SKIP: worktree ya existe: ${path}"
SKIPPED=$((SKIPPED + 1))
continue
fi
# Verificar que la branch no existe ya
if git show-ref --verify --quiet "refs/heads/${branch}" 2>/dev/null; then
echo "WARN: branch ${branch} ya existe, creando worktree desde ella"
git worktree add "$path" "$branch" 2>/dev/null || {
echo "FAIL: no se pudo crear worktree para ${slug}"
FAILED=$((FAILED + 1))
continue
}
else
echo "CREATE: worktree ${path} (branch ${branch})"
git worktree add -b "$branch" "$path" master 2>/dev/null || {
echo "FAIL: no se pudo crear worktree para ${slug}"
FAILED=$((FAILED + 1))
continue
}
fi
CREATED=$((CREATED + 1))
done
echo ""
echo "=== Resumen ==="
echo "Creados: ${CREATED}"
echo "Existentes: ${SKIPPED}"
echo "Fallidos: ${FAILED}"
echo ""
echo "=== Worktrees activos ==="
git worktree list
@@ -0,0 +1,165 @@
#!/bin/bash
# verify-worktree.sh — Verifica build, tests y cierre de issue en un worktree.
#
# Uso:
# ./verify-worktree.sh <worktree-path> [build-cmd] [test-cmd]
#
# Ejemplos:
# ./verify-worktree.sh worktrees/0026-foo
# ./verify-worktree.sh worktrees/0026-foo "go build -tags fts5 ./..." "go test -tags fts5 ./..."
# BUILD_CMD="cmake --build cpp/build" TEST_CMD="ctest --test-dir cpp/build" ./verify-worktree.sh worktrees/0026-foo
#
# Resolucion de comandos (en orden de prioridad):
# 1. Argumentos posicionales (build-cmd, test-cmd)
# 2. Variables de entorno BUILD_CMD / TEST_CMD
# 3. Archivo .parallel-fix-issues.yml en la raiz del worktree (claves: build, test)
# 4. Auto-deteccion segun ficheros del proyecto:
# - go.mod → "go build ./..." + "go test ./..."
# - CMakeLists.txt → "cmake -S . -B build && cmake --build build" + "ctest --test-dir build"
# - Cargo.toml → "cargo build" + "cargo test"
# - package.json → "npm run build" + "npm test"
# - pyproject.toml → "" + "pytest"
# 5. Si nada se detecta, salta build/test con WARN.
#
# Auto-deteccion adicional: si hay go.mod, intenta extraer build tag de //go:build.
#
# Exit codes:
# 0 = todo OK
# 1 = error de argumento
# 2 = build fallo
# 3 = tests fallaron
# 4 = issue no cerrado (solo WARN, no falla)
# 5 = sin commits propios
set -euo pipefail
if [ $# -lt 1 ]; then
echo "ERROR: se necesita el path del worktree"
echo "Uso: $0 <worktree-path> [build-cmd] [test-cmd]"
exit 1
fi
WORKTREE="$1"
ARG_BUILD_CMD="${2:-}"
ARG_TEST_CMD="${3:-}"
# Resolver path absoluto
if [[ "$WORKTREE" != /* ]]; then
REPO_ROOT="$(git rev-parse --show-toplevel)"
WORKTREE="${REPO_ROOT}/${WORKTREE}"
fi
if [ ! -d "$WORKTREE" ]; then
echo "ERROR: worktree no encontrado: ${WORKTREE}"
exit 1
fi
SLUG="$(basename "$WORKTREE")"
echo "=== Verificando: ${SLUG} ==="
# --- Resolver build/test commands ---
BUILD_CMD="${ARG_BUILD_CMD:-${BUILD_CMD:-}}"
TEST_CMD="${ARG_TEST_CMD:-${TEST_CMD:-}}"
# Manifest opcional
MANIFEST="${WORKTREE}/.parallel-fix-issues.yml"
if [ -z "$BUILD_CMD" ] && [ -f "$MANIFEST" ]; then
M_BUILD=$(grep -E "^build:" "$MANIFEST" 2>/dev/null | sed -E 's/^build:[[:space:]]*"?([^"]*)"?[[:space:]]*$/\1/' | head -1 || true)
if [ -n "$M_BUILD" ]; then BUILD_CMD="$M_BUILD"; echo "INFO: build desde manifest"; fi
fi
if [ -z "$TEST_CMD" ] && [ -f "$MANIFEST" ]; then
M_TEST=$(grep -E "^test:" "$MANIFEST" 2>/dev/null | sed -E 's/^test:[[:space:]]*"?([^"]*)"?[[:space:]]*$/\1/' | head -1 || true)
if [ -n "$M_TEST" ]; then TEST_CMD="$M_TEST"; echo "INFO: test desde manifest"; fi
fi
# Auto-deteccion
if [ -z "$BUILD_CMD" ] || [ -z "$TEST_CMD" ]; then
AUTO_BUILD=""
AUTO_TEST=""
if [ -f "${WORKTREE}/go.mod" ]; then
# Detectar build tag
AUTO_TAG=$(grep -rh "^//go:build " --include="*.go" "$WORKTREE" 2>/dev/null \
| sed -E 's|^//go:build ([a-zA-Z0-9_]+).*|\1|' \
| sort -u | head -1 || true)
TAG_FLAG=""
[ -n "$AUTO_TAG" ] && TAG_FLAG="-tags $AUTO_TAG"
AUTO_BUILD="go build $TAG_FLAG ./..."
AUTO_TEST="go test $TAG_FLAG ./..."
echo "INFO: stack detectado: Go${TAG_FLAG:+ ($TAG_FLAG)}"
elif [ -f "${WORKTREE}/CMakeLists.txt" ] || ls "${WORKTREE}"/cpp/CMakeLists.txt >/dev/null 2>&1; then
CMAKE_DIR="."
[ -f "${WORKTREE}/cpp/CMakeLists.txt" ] && [ ! -f "${WORKTREE}/CMakeLists.txt" ] && CMAKE_DIR="cpp"
AUTO_BUILD="cmake -S ${CMAKE_DIR} -B ${CMAKE_DIR}/build -DCMAKE_BUILD_TYPE=Release && cmake --build ${CMAKE_DIR}/build -j"
AUTO_TEST="ctest --test-dir ${CMAKE_DIR}/build --output-on-failure || true"
echo "INFO: stack detectado: C++/CMake (dir=${CMAKE_DIR})"
elif [ -f "${WORKTREE}/Cargo.toml" ]; then
AUTO_BUILD="cargo build"
AUTO_TEST="cargo test"
echo "INFO: stack detectado: Rust"
elif [ -f "${WORKTREE}/package.json" ]; then
AUTO_BUILD="npm run build --if-present"
AUTO_TEST="npm test --if-present"
echo "INFO: stack detectado: Node"
elif [ -f "${WORKTREE}/pyproject.toml" ] || [ -f "${WORKTREE}/setup.py" ]; then
AUTO_BUILD="" # python normalmente no tiene build step
AUTO_TEST="pytest"
echo "INFO: stack detectado: Python"
else
echo "WARN: no se detecto stack; usar BUILD_CMD/TEST_CMD env o manifest .parallel-fix-issues.yml"
fi
[ -z "$BUILD_CMD" ] && BUILD_CMD="$AUTO_BUILD"
[ -z "$TEST_CMD" ] && TEST_CMD="$AUTO_TEST"
fi
# 1. Verificar commits propios
echo ""
echo "--- Commits propios ---"
COMMIT_COUNT=$(cd "$WORKTREE" && git log master..HEAD --oneline 2>/dev/null | wc -l)
if [ "$COMMIT_COUNT" -eq 0 ]; then
echo "FAIL: sin commits propios en la branch"
exit 5
fi
echo "OK: ${COMMIT_COUNT} commits desde master"
cd "$WORKTREE" && git log master..HEAD --oneline
# 2. Build
echo ""
if [ -n "$BUILD_CMD" ]; then
echo "--- Build ($BUILD_CMD) ---"
if (cd "$WORKTREE" && bash -c "$BUILD_CMD" 2>&1); then
echo "OK: build exitoso"
else
echo "FAIL: build fallo"
exit 2
fi
else
echo "--- Build SKIPPED (sin comando) ---"
fi
# 3. Tests
echo ""
if [ -n "$TEST_CMD" ]; then
echo "--- Tests ($TEST_CMD) ---"
if (cd "$WORKTREE" && bash -c "$TEST_CMD" 2>&1); then
echo "OK: tests pasaron"
else
echo "FAIL: tests fallaron"
exit 3
fi
else
echo "--- Tests SKIPPED (sin comando) ---"
fi
# 4. Issue cerrado
echo ""
echo "--- Cierre de issue ---"
COMPLETED_FILES=$(cd "$WORKTREE" && git diff --name-only master -- dev/issues/completed/ 2>/dev/null | wc -l)
if [ "$COMPLETED_FILES" -gt 0 ]; then
echo "OK: issue movido a completed/"
cd "$WORKTREE" && git diff --name-only master -- dev/issues/completed/
else
echo "WARN: no se detecto issue movido a completed/ (verificar manualmente)"
fi
echo ""
echo "=== RESULTADO: ${SLUG} — OK ==="
+8
View File
@@ -80,3 +80,11 @@ Thumbs.db
broken_paths.txt
imgui.ini
prompts/
kotlin/functions/ui/
# Module versioning auto-generated headers (written by `fn index`, issue 0097)
**/version_generated.h
**/app_modules_generated.h
# Issue migration backups (0100)
dev/issues/.backup_pre_*
+6
View File
@@ -14,3 +14,9 @@
[submodule "cpp/vendor/implot3d"]
path = cpp/vendor/implot3d
url = https://github.com/brenocq/implot3d.git
[submodule "cpp/vendor/sdl3"]
path = cpp/vendor/sdl3
url = https://github.com/libsdl-org/SDL.git
[submodule "emsdk"]
path = emsdk
url = https://github.com/emscripten-core/emsdk.git
+2 -5
View File
@@ -1,11 +1,8 @@
{
"mcpServers": {
"registry": {
"command": "/home/lucas/fn_registry/apps/registry_mcp/registry_mcp",
"args": ["--enable-run", "--enable-write"],
"env": {
"FN_REGISTRY_ROOT": "/home/lucas/fn_registry"
}
"command": "./apps/registry_mcp/registry_mcp",
"args": ["--enable-run", "--enable-write"]
}
}
}
+100
View File
@@ -8,6 +8,106 @@ Para contexto detallado del trabajo diario ver `docs/diary/`. Para decisiones ar
## [Unreleased]
## 2026-05-17
### Added
- **Bloque `service:` en frontmatter de `app.md`** (issue 0105) — toda app con `tag: service` declara ahora `port`, `health_endpoint`, `health_timeout_s`, `systemd_unit`, `systemd_scope`, `restart_policy`, `runtime` (`systemd-user|systemd-system|docker-compose|stdio|manual`), `pc_targets[]`, `is_local_only`. 11 apps actualizadas: `sqlite_api`, `dag_engine`, `call_monitor`, `kanban`, `deploy_server`, `registry_mcp`, `registry_api`, `footprint_geo_stack`, `element_matrix_chat`, `agents_and_robots`, `services_api`.
- **Migration `014_service_metadata.sql`** — anade 8 columnas (`service_port`, `service_health_endpoint`, `service_health_timeout_s`, `service_systemd_unit`, `service_systemd_scope`, `service_restart_policy`, `service_runtime`, `service_is_local_only`) a `apps` + tabla nueva `service_targets (app_id, pc_id, role)` con indices por `app_id` y `pc_id`.
- **`registry.App.Service *ServiceSpec`** + parser `rawService` + escritura/lectura en `InsertApp`/`scanApps`/`Purge` (preserva `service_targets`). API publica `db.GetServicePCTargets(appID) []string`.
- **`audit_services_spec_go_infra`** (`functions/infra/audit_services_spec.{go,md}`) — audita apps `tag: service` y reporta drift del bloque `service:` (runtime allowlist, pc_targets >=1, systemd_unit obligatorio si `runtime` empieza con `systemd-`, restart_policy en `always|on-failure|none`).
- **`fn doctor services-spec`** — subcomando nuevo en `cmd/fn/doctor.go`. Salida tabwriter + `--json`. Hoy: `11/11 services with complete service: block`.
- **App `services_api`** (`apps/services_api/`, issue 0106) — Go HTTP daemon en `127.0.0.1:8485`. Loop paralelo cada 15s (max 8 in-flight, timeout 20s/probe) que reconcilia esperado vs real para cada `(app, pc)` cruzado de `service_targets`. Probes locales (`systemctl is-active` + TCP dial + `http.Client`) o remotos (`ssh_exec_go_infra`). Persiste en `operations.db`: `service_state` (snapshot actual) + `service_transition` (cambios de overall append-only). Endpoints `GET /api/health`, `GET /api/services`, `POST /api/check`, `GET /api/pcs`. systemd unit `~/.config/systemd/user/services_api.service` con `Restart=always`.
- **App `services_monitor`** (`apps/services_monitor/`, issue 0106) — frontend C++ ImGui. Polling auto cada 5s configurable + boton "Force check" (POST `/api/check`). Tabla 9-col agrupada por app: overall pill, systemd state, port + listening flag (`TI_PLUG`/`TI_PLUG_CONNECTED`), HTTP status+latency, runtime, last change age, error/note. JSON via `vendor/nlohmann/json.hpp` (copiado de data_factory). HTTP socket TCP via `http_client.{cpp,h}` (copiado de data_factory). Build linux + windows con `add_imgui_app` + ws2_32 en Win. Deploy automatico via `redeploy_cpp_app_windows`.
- **Issues 0105 + 0106** (`dev/issues/`) — estandarizacion del bloque `service:` y app `services_monitor`.
### Fixed
- **`sqlite_api.service` murio 20h sin alerta el 2026-05-17** — Raiz: el unit tenia `Restart=on-failure` y el ultimo exit fue por `SIGTERM` (limpio, no failure). systemd NO reinicia exit success. Fix: cambio a `Restart=always` + `RestartSec=5`. Reload + restart inmediato. Detectado mientras se debuggeaba `data_factory` cargando lento (raiz: data_factory llama a `sqlite_api:8484`, timeout 3s, no responde). Aplicado el mismo `Restart=always` al unit nuevo `services_api.service`.
- **`sqlite_api/app.md` health_endpoint** — declaraba `/api/status` que devuelve 404. Cambiado a `/api/databases` (200, lista de bases registradas). Detectado por el primer ciclo del propio `services_api` que marcaba sqlite_api como `degraded`.
### Changed
- **`services_monitor` tags** — sin `service`/`services` en `tags` para evitar falso positivo en el matcher `tags LIKE '%service%'` del audit `services-spec`. La app es desktop client (frontend), no daemon.
## 2026-05-16
### Added
- **Panel "Logs" en `dag_engine` RunDetail** — `apps/dag_engine/frontend/src/pages/RunDetail.tsx` anade `<Paper>` final con `<Code block>` scrollable + `CopyButton` de Mantine. Helper `buildLogText(run, steps)` compone texto plano (metadata del run + por-step status/exit/duration/stdout/stderr indentado) para pegar entero al LLM sin abrir los `Collapse` del `StepTimeline`.
### Fixed
- **`dag_engine` steps `function:` fallando con `error: function "<id>" not found (tried as ID and name)`** — tres DAGs nocturnos (`fn_backup` x2, `daily-registry-audit`) fallaron 2026-05-15/16 porque el binario `fn` resolvia una copia stale `apps/dag_engine/registry.db` (May 15, 262 KB) en vez del `registry.db` raiz. Raiz: el systemd unit `dag_engine.service` tiene `WorkingDirectory=apps/dag_engine/` y no exportaba `FN_REGISTRY_ROOT`; `cmd/fn/ops.go::tryOpenRegistryDB` cae al walk-up `go.mod` (devuelve `apps/dag_engine/`). Fix:
- Borrado `apps/dag_engine/registry.db` stale (violaba `.claude/rules/db_locations.md`).
- `~/.config/systemd/user/dag_engine.service`: anadido `Environment=FN_REGISTRY_ROOT`, `FN_BIN`, `PATH` (con `/usr/local/go/bin` para steps `function:` Go sin tests que invocan `go vet`), `HOME`.
- `apps/dag_engine/executor.go`: steps `function:` exportan `FN_REGISTRY_ROOT=<root>` en env y default `dir = fnRegistryRoot` si `step.Dir`/`dag.WorkingDir` vacios. Steps `command:`/`script:` sin cambio.
### Added
- **Iconos `.ico` Windows para apps C++** — 11 apps GUI (`chart_demo`, `dag_engine_ui`, `data_factory`, `graph_explorer`, `navegator_dashboard`, `odr_console`, `primitives_gallery`, `registry_dashboard`, `shaders_lab`, `text_editor_smoke`, `altsnap_jitter_test`) ahora tienen icono propio en el `.exe` y en `<exe_dir>` desplegado.
- Glyphs: **Phosphor Icons** (`fill` weight), clonado en `sources/phosphor-core/` (1512 SVGs disponibles). Cada app usa un `accent_hex` distinto (Tailwind 500-700) para distinguirse en taskbar/desktop.
- Mapping inicial en `dev/gen_app_icons.py` (script reproducible). Cada `.ico` multi-resolucion (16/24/32/48/64/128/256).
- Wiring CMake: `cpp/CMakeLists.txt:1-5` declara `LANGUAGES C CXX RC` en WIN32; `add_imgui_app` macro detecta `<app_dir>/appicon.ico` y genera `<target>_appicon.rc` enlazado via `windres` (toolchain `cpp/toolchains/mingw-w64.cmake`).
- Nueva funcion del registry: `generate_app_icon_py_infra` (`python/functions/infra/generate_app_icon.{py,md}`). Toma `phosphor_icon_name + accent_hex + out_ico_path` y exporta `.ico` multi-res. Tags: `cpp-windows`, `icon`, `phosphor`.
- Convencion documentada en `.claude/rules/cpp_apps.md §11`.
- **C++ framework — Alt+RMB resize / Alt+LMB move anywhere** (`cpp/framework/app_base.cpp`). WndProc subclass detecta `WM_RBUTTONDOWN`/`WM_LBUTTONDOWN` con `GetAsyncKeyState(VK_MENU) & 0x8000`, `ReleaseCapture` + `PostMessage(WM_SYSCOMMAND, SC_SIZE|dir | SC_MOVE|HTCAPTION)`. Modal nativo, cero jitter automatico via gate sizemove existente. Aplica a main + cada viewport flotante (subclass per-frame).
- **C++ framework — multi-HWND subclass** para anti-jitter. `g_subclassed` ahora `unordered_map<HWND, WNDPROC>`, scan per-frame en `pio.Viewports` instala subclass en cada HWND nuevo, `prune_dead_subclassed()` con `IsWindow`, `uninstall_sizemove_subclass_all()` al exit. Fix del temblor en paneles flotantes (no solo el main HWND).
- **C++ framework — iconified survival** de paneles flotantes. Antes `glfwWaitEvents+continue` paraba el frame loop entero al minimizar el main → secondary viewports congelados/ocultos. Ahora detecta secondary viewports y fall-through al frame normal si existen; solo duerme cuando no hay flotantes.
- **C++ framework — `fn::internal::*` test observability**. `sizemove_enter_count()`, `alt_rmb_resize_count()`, `alt_lmb_move_count()`, `rbuttondown_seen_count()`, `set_force_alt_for_test(bool)`. Counters monotonicos zero-cost, modo test salta `PostMessage SC_SIZE/SC_MOVE` para no atrapar al harness en modal.
- **`apps/altsnap_jitter_test/`** — extendido a 6 phases (p1 sync, p2 main HWND modal, p3 secondary HWND modal, p4 iconify+restore preserva floating, p5 Alt+RMB consumed, p6 Alt+LMB consumed). Todas PASS en Windows.
- **`redeploy_all_cpp_apps_bash_pipelines`** — pipeline nuevo `bash/functions/pipelines/redeploy_all_cpp_apps.sh` que cross-compila todo el arbol `cpp/` en un solo cmake pass + redeploy de cada `.exe` al Desktop. Filtro opcional por substring de nombre. Tolerante a fallos (build best-effort, summary OK/SKIPPED/FAILED). Tags: `cpp, windows, deploy, redeploy, bulk, cpp-windows`. Composicion: `build_cpp_windows_bash_infra` + loop `taskkill.exe` + `deploy_cpp_exe_to_windows_bash_infra`.
### Changed
- **`io.ConfigWindowsMoveFromTitleBarOnly = true`** en `fn::run_app`. Floating panels (viewport secundario = OS window borderless con UNA ventana ImGui rellenandolo) ahora respetan "solo header arrastra" como las decoradas. Fix del drag-anywhere-sin-alt en panel flotante. Alt+LMB anywhere sigue funcionando (subclass consume antes que ImGui).
- **`resolve_cpp_app_dir_bash_infra` v1.1.0** — ahora busca apps tambien en `apps/<X>/` (canonical issue 0096) ademas de `cpp/apps/<X>/` (legacy) y `projects/*/apps/<X>/`. Fix retroactivo: `./fn run compile_cpp_app <name>` fallaba para apps en el layout canonical (ej. `dag_engine_ui`). Deduccion desde CWD tambien actualizada. Helper interno `_list_cpp_apps`.
### Notes
- Apps C++ redesplegadas via `redeploy_all_cpp_apps`: 12 OK / 1 SKIP (`data_factory` sin .exe target) / 0 FAILED. Todas tienen los fixes del framework activos.
- ImGui_ImplGlfw subclassea el HWND DESPUES que nuestro framework. ImGui captura nuestro WndProc como `PrevWndProc` y chainea via `CallWindowProc`, asi que el subclass nuestro sigue recibiendo TODOS los mensajes en el orden correcto. NO re-subclassear despues de ImGui init (provoca recursion infinita por cycle: `our_proc -> orig=imgui_proc -> imgui_proc -> prev=our_proc -> ...`).
- Pre-existing build break en `cpp/tests/test_llm_anthropic.cpp` + `cpp/tests/test_graph_icons.cpp` por uso de `setenv()` que no existe en mingw-w64. NO bloquea `redeploy_all_cpp_apps` (build best-effort). Candidato a guard `#ifdef _WIN32` con `_putenv_s` o skip cross-compile. No introducido por esta sesion.
## 2026-05-14
### Added
- **Issue 0086 — Monitor tab del `registry_dashboard`** (sub-repo `dataforge/registry_dashboard`). Pestaña `Monitor` primera y por defecto del TabBar, landing del bucle reactivo construir->ejecutar->recopilar->analizar->mejorar.
- 7 KPIs (Calls / MCP / Reg % / Errors / Violations / Copies / Versions) filtradas por ventana temporal (1h/24h/7d/30d/All).
- Sub-tab `Recent Executions` con columnas When/Function/Tool/ms/OK/Error. Columna Function muestra `$ <snippet>` en gris cuando `function_id` vacio, hover tooltip con comando completo. Checkbox `Only registry functions` filtra por `function_id != ''`.
- Sub-tab `Failed Functions` (5a) — subset filtrado a registry-functions fallidas, columnas When/Function/Tool/Error class/Error snippet, function_id en rojo.
- Live scatter `duracion (ms)` vs `time`: eje X auto-scroll a `now`, ventana configurable (1m/5m/15m/1h/6h) independiente del filtro de KPIs, eje Y dinamico `0..max(visible)+500ms`. Hora local (`UseLocalTime`). Series ok/error en verde/rojo. Hover sobre punto = tooltip Function/Tool/Duration/Error.
- Indicador `live`/`offline` con timestamp del ultimo evento WS.
- **WebSocket live stream sqlite_api -> registry_dashboard** (sub-repo `dataforge/sqlite_api`). Endpoint `GET /api/events/call_monitor`. Hub global con subscribers; ticker arranca solo con >=1 subscriber (cero overhead si nadie mira). Cliente recibe snapshot inicial (KPIs + 100 ultimas filas + watermark) y luego deltas `id > watermark`. Cliente puede mandar `{watermark: N}` para resumir tras reconexion.
- **WS client C++** hand-rolled RFC6455 en `ws_client.{h,cpp}` (~330 LOC) en el dashboard. Localhost-only (no TLS). Thread propio, reconnect exponencial 0.5s->8s, FIN/text/ping/pong/close handling, queue thread-safe drenada cada frame.
- **Migration 007 `command_snippet` en `calls`** (`projects/fn_monitoring/apps/call_monitor/migrations/007_calls_command_snippet.sql`). Aditiva, idempotente. Llena por hook `hook_call_monitor.sh` solo cuando `function_id == ''`. Redactado de `password=`/`token=`/`secret=`/`api_key=`/`bearer=`. Truncado 200 chars.
- **Issue 0087 — Capability Discovery Acceleration**. Modelo 5 capas + 7 piezas (ver `dev/issues/0087-*.md`).
- **`fn match`** (`cmd/fn/match.go`) — subcommand fuzzy-FTS5 que dado un comando devuelve top-N funciones del registry candidates. Latencia 6-7ms. Output JSON con `score` (normalizado top=1.0) + `raw_score` (absoluto pre-normalizacion) + `high_confidence` gate (`raw_score >= 4.0 AND top1.raw/top2.raw > 1.5`).
- **`fn doctor capabilities --emit-claude-md`** (`cmd/fn/doctor.go` + `functions/infra/emit_capabilities_md.go`) — emite bloque markdown con secciones TOP 20 (por `calls_total`), Fresh 7d, Pipelines top 5. Fallback si `call_monitor.operations.db` ausente.
- **`call_monitor sequences --detect [--propose]`** (`projects/fn_monitoring/apps/call_monitor/sequences.go` + `migrations/006_function_sequences.sql`). Detecta secuencias A->B(->C) en `calls` (same session, gap < 30s, occ >= 5, sess >= 2, success_rate >= 0.9) y abre proposals `new_pipeline` automaticamente.
- **Hook `PreToolUse` `hook_fn_match.sh`** — denylist + `fn match` con timeout 0.2s. Inyecta `<system-reminder>FUZZY-MATCH: USE ./fn run <id>` cuando confidence alta. Latencia 113ms trigger / 32ms denylist. Registrado en `.claude/settings.local.json` (Bash matcher).
- **Hook `UserPromptSubmit` `hook_capabilities_inject.sh`** — cache 1h en `~/.cache/fn_registry/capabilities.txt`. Emite JSON `hookSpecificOutput.additionalContext` con linea compacta `CAPABILITIES: TOP / FRESH / PIPELINES`. Latencia cold 33ms / warm 18ms.
- **Timer systemd user** `call_monitor_sequences.timer` (OnCalendar 0/6h) + `.service` oneshot ejecutando `call_monitor sequences --detect --propose --report`. Versionado en `projects/fn_monitoring/apps/call_monitor/systemd/`.
- **3 funciones nuevas grupo `cpp-windows`** + pagina madre `docs/capabilities/cpp-windows.md`:
- `launch_cpp_app_windows_bash_infra``cmd.exe`/`PowerShell Start-Process` para lanzar exe en Windows desde WSL2.
- `is_cpp_app_running_windows_bash_infra``tasklist.exe /FI` con exit code 0/1 + stdout `RUNNING: PID=N MEM=K` o `NOT_RUNNING`.
- `redeploy_cpp_app_windows_bash_pipelines` — pipeline build? + deploy + launch + verify en 1 invocacion. Reemplaza ~6 commands manuales.
- **ADR 0004 `docs/adr/0004-telemetry-driven-capability-growth.md`** — formaliza el bucle telemetria -> proposal -> capability group -> discovery acceleration como motor de crecimiento del registry.
- **Regla `.claude/rules/function_growth_and_self_docs.md`** (entry #30 en `INDEX.md`) — contrato `.md` autosuficiente (Ejemplo + Cuando usarla + Gotchas + Growth log) + crecimiento del registry por promocion de composiciones, NO por inflado de funciones individuales.
### Changed
- **`.claude/CLAUDE.md` Norte ampliado** — 4o objetivo `PROMOVER COMPOSICIONES A PIPELINES` (el registry crece por composicion, no por inflado). Linea sobre auto-discovery zero-second-lookup.
- **`.claude/rules/registry_calls.md`** — clausula nueva: hooks e infraestructura de telemetria (`fn_match`, `fn doctor`, `call_monitor`) pueden leer `registry.db` directo con conexion read-only. NO sujeto a regla MCP-first (no son acciones del agente).
- **`/fn_claude` command** mejorado con objetivos del Monitor + interpretacion de `FUZZY-MATCH` hint + `CAPABILITIES` line + threshold semantica.
### Fixed
- **`launch_cpp_app_windows` quoting bug** — `cmd.exe /c "cd /d \"$dir\" && start ..."` rompia con paths Windows (el `\"` final se interpretaba como escape de comilla -> string sin cerrar -> "Windows cannot find \\"). Fix: reescribir a `powershell.exe -Command "Start-Process -FilePath ... -WorkingDirectory ..."` (single-quote PowerShell es literal, sin procesar `\` ni `$`).
- **`fn match high_confidence` siempre true** — debido a normalizacion `top=1.0`. Fix: añadir `raw_score` preservado pre-normalizacion + gate dual `raw_score >= 4.0 AND top1.raw/top2.raw > 1.5`. Threshold 4.0 tuneado contra 14 patrones del analysis `domain_coverage_gaps` (~93% precision).
## 2026-05-07
### Added
+4
View File
@@ -0,0 +1,4 @@
[2026-05-15 23:51:43.764] [INFO] app start: altsnap_jitter_test
[2026-05-15 23:51:44.017] [INFO] app exit
[2026-05-15 23:52:47.933] [INFO] app start: altsnap_jitter_test
[2026-05-15 23:52:48.135] [INFO] app exit
+360
View File
@@ -0,0 +1,360 @@
# dag_engine — Guia de uso
Motor de DAGs propio del fn_registry. **Scheduler oficial** del ecosistema (issue 0007a-e + flow 0001). Backend Go + frontend web (Vite/React) + frontend C++ ImGui (`cpp/apps/dag_engine_ui`).
Doc canonica para **anadir DAGs**, **formato YAML**, **comandos CLI**, y **diagnostico de fallos**.
---
## 1. Donde viven los DAGs
| Path | Que |
|---|---|
| `apps/dag_engine/dags_migrated/` | DAGs activos servidos por `dag_engine.service` (systemd user unit). |
| `apps/dag_engine/dags_migrated/archive/` | DAGs deshabilitados (no se cargan por el scheduler). |
Por defecto el systemd unit apunta a `apps/dag_engine/dags_migrated/`. Para usar otro dir, edita `~/.config/systemd/user/dag_engine.service`:
```ini
ExecStart=/home/lucas/fn_registry/apps/dag_engine/dag_engine server \
--port 8090 \
--dags-dir /home/lucas/fn_registry/apps/dag_engine/dags_migrated \
--db /home/lucas/fn_registry/apps/dag_engine/dag_engine.db \
--scheduler
```
Y reload + restart:
```bash
systemctl --user daemon-reload
systemctl --user restart dag_engine.service
```
---
## 2. Anadir un DAG nuevo (workflow)
### Paso a paso
1. **Crear YAML** en `apps/dag_engine/dags_migrated/<nombre>.yaml` (ver formato en seccion 3).
2. **Validar** sin ejecutar:
```bash
./apps/dag_engine/dag_engine validate apps/dag_engine/dags_migrated/<nombre>.yaml
```
Salida esperada: `Validation: PASS`. Si falla, ver seccion 5 (diagnostico).
3. **Probar ejecucion manual** una vez:
```bash
./apps/dag_engine/dag_engine run apps/dag_engine/dags_migrated/<nombre>.yaml
```
4. **Recargar scheduler** (toma el YAML automaticamente al iterar el dir):
```bash
systemctl --user restart dag_engine.service
journalctl --user-unit dag_engine.service -n 30 --no-pager
```
Busca la linea `[scheduler] ticker started for <nombre> (<cron>)` en los logs.
5. **Verificar en frontend**:
- C++ ImGui: panel `DAGs` muestra el nuevo DAG. Pulsa `Refresh` si no aparece.
- Web: `http://localhost:8090`.
### Disparo manual desde curl o frontend
```bash
curl -X POST http://127.0.0.1:8090/api/dags/<nombre>/run
```
Devuelve `{"dag":"<nombre>","run_id":"...","status":"accepted"}` y dispara el WS broadcast — los frontends ven la run en `<1s`.
---
## 3. Formato YAML
Formato YAML propio de dag_engine. Schema: `name`, `description`, `schedule`, `env`, `tags`, `working_dir`, `steps[]`, `handlers` (alias `handler_on`).
### Ejemplo completo
```yaml
name: my_pipeline
description: "Pipeline diario que importa CSV y actualiza Metabase."
group: finanzas # opcional, agrupa DAGs en listados
type: graph # opcional: graph (default) | chain
tags: [daily, csv, metabase] # opcional, filtros en la UI
# Variables de entorno (heredadas por todos los steps).
env:
- DATA_DIR: /home/lucas/data
- SLACK_HOOK: ${SLACK_HOOK_PROD} # interpolacion de ENV del host
# Cron schedule. Puede ser string o lista.
schedule:
- "0 9 * * *" # 09:00 todos los dias
- "0 21 * * 5" # 21:00 viernes (segundo trigger)
# Working dir + shell por defecto para todos los steps.
working_dir: /home/lucas/fn_registry
shell: /bin/bash
timeout_sec: 1800 # 30 min para todo el DAG
steps:
- name: ingest
description: "Descarga CSV."
command: ./bash/functions/pipelines/ingest_csv.sh
timeout_sec: 300 # 5 min para este step
env:
- SOURCE_URL: https://example.com/data.csv
- name: transform
description: "Limpieza y agregacion."
script: |
#!/usr/bin/env python3
import pandas as pd
df = pd.read_csv("$DATA_DIR/raw.csv")
df.to_parquet("$DATA_DIR/clean.parquet")
depends: [ingest] # debe terminar OK antes
retry_policy:
limit: 2 # reintentos en caso de fallo
interval_sec: 60
- name: load_metabase
command: ./bash/functions/metabase/refresh_dashboard.sh
depends: [transform]
continue_on:
failure: true # no aborta el DAG aunque falle
- name: notify
command: ./bash/functions/io/slack_send.sh "pipeline OK"
depends: [load_metabase]
# Hooks de ciclo de vida.
handler_on:
success: ./bash/functions/io/notify_success.sh
failure: ./bash/functions/io/notify_failure.sh
exit: ./bash/functions/io/cleanup.sh
```
### Campos del DAG (top-level)
| Campo | Tipo | Default | Que |
|---|---|---|---|
| `name` | string | (obligatorio) | Identificador unico. Debe matchear el filename sin extension. |
| `description` | string | "" | Texto libre, aparece en la UI. |
| `group` | string | "" | Agrupa DAGs en listados. |
| `type` | string | `""` (graph) | `graph` o `chain`. graph = grafo dirigido por `depends`. chain = ejecucion secuencial implicita. |
| `working_dir` | string | cwd del server | Path absoluto desde donde lanzar los steps. |
| `shell` | string | `/bin/sh` | Shell para `command:`. |
| `env` | list/map | [] | Variables de entorno DAG-wide. |
| `schedule` | string/list | "" | Cron expressions (5 campos: min hour dom mon dow). Vacio = solo manual. |
| `steps` | list | (obligatorio) | Pasos del DAG (>=1). |
| `handler_on` | map | null | Hooks `init/success/failure/exit`. Alias: `handlers`. |
| `tags` | list[string] | [] | Filtros en la UI. |
| `timeout_sec` | int | 0 (sin timeout) | Timeout global del DAG en segundos. |
### Campos de cada step
| Campo | Tipo | Default | Que |
|---|---|---|---|
| `name` | string | (obligatorio) | Identificador del step dentro del DAG. |
| `id` | string | "" | Override del id auto-generado. |
| `description` | string | "" | Texto libre. |
| `command` | string | "" | Comando shell (mutuamente excluyente con `script`/`function`). |
| `script` | string | "" | Bloque heredoc. Util para Python/Lua inline. |
| `function` | string | "" | ID de funcion del registry (ej `audit_capability_groups_go_infra`). Si set, executor invoca `${FN_REGISTRY_ROOT}/fn run <id> <args...>` y captura `function_id` en `dag_step_results`. Mutuamente exclusivo con `command`/`script`; si convive, gana `function`. |
| `args` | list[string] | [] | Args extra para `command` o para la `function`. |
| `shell` | string | hereda | Override del shell. |
| `dir` / `working_dir` | string | hereda | Working dir para este step. |
| `depends` | list[string] | [] | Steps que deben terminar OK antes. Si vacio + `type:graph`, arranca en paralelo. |
| `env` | list/map | hereda | Env del step (sobrescribe el del DAG). |
| `continue_on.failure` | bool | false | Si true, el DAG sigue aunque este step falle. |
| `continue_on.skipped` | bool | false | Si true, dependientes corren aunque este step quede skipped. |
| `retry_policy.limit` | int | 0 | Reintentos. |
| `retry_policy.interval_sec` | int | 0 | Segundos entre reintentos. |
| `timeout_sec` | int | 0 (sin timeout) | Timeout del step. |
| `output` | string | "" | Nombre de variable donde guardar stdout (consumible por dependientes). |
| `tags` | list[string] | [] | Tags por step (UI). |
### Function steps (coherencia con el registry)
Un DAG idiomatico llama funciones del registry, no scripts ad-hoc. Cada step `function:` queda trazado en `call_monitor.calls` por el hook PostToolUse del agente y en `dag_step_results.function_id` del propio dag_engine — el bucle reactivo (issue 0085) tiene visibilidad end-to-end.
```yaml
steps:
- name: audit_capabilities
function: audit_capability_groups_go_infra
args: ["--json"]
description: "Audita drift entre tags de capability group y paginas madre"
```
Ventajas vs `command: ./fn run ...`:
- `function_id` se persiste como columna dedicada en `dag_step_results` (filtrable, agrupable).
- El frontend `dag_engine_ui` muestra badge + panel lateral con `uses_functions` (subfunciones que el step va a usar transitivamente).
- API: `GET /api/functions/{id}` devuelve `{id, name, description, signature, purity, domain, lang, uses_functions[], uses_types[]}` leyendo `registry.db` read-only. La UI consume este endpoint al expandir un step.
- Validator regex en `dag_validate`: `^[a-z0-9_]+_[a-z]+_[a-z]+$`. ID invalido = error.
- Variables de entorno: `FN_REGISTRY_ROOT` (default `/home/lucas/fn_registry`) localiza el binario `fn`. Override con `FN_BIN=/path/al/fn`.
- **`FN_REGISTRY_ROOT` obligatorio cuando el servicio corre via systemd** con `WorkingDirectory` fuera del root del registry. El binario `fn` resuelve `registry.db` por (1) env var, (2) walk-up buscando `go.mod`, (3) exe dir. Si (1) no esta y (2) encuentra el `go.mod` del propio servicio (ej. `apps/dag_engine/go.mod`), devuelve un dir donde `registry.db` no existe o esta stale, fallando con `error: function "<id>" not found`. Bug historico: `apps/dag_engine/registry.db` stale (May 15) tumbo 3 noches `fn_backup` + `daily-registry-audit`. Defensa en profundidad: el executor exporta `FN_REGISTRY_ROOT` y hace `cd $FN_REGISTRY_ROOT` antes del spawn de steps `function:` (executor.go), pero el `Environment=FN_REGISTRY_ROOT=...` del systemd unit sigue siendo la fuente de verdad.
- **`PATH` en el systemd unit**: si steps `function:` invocan funciones Go sin tests (`go vet`) o Python (`python3`), el `PATH` del entorno systemd debe incluir esos binarios — declarar `Environment=PATH=/usr/local/go/bin:/home/lucas/go/bin:/home/lucas/.local/bin:/usr/local/bin:/usr/bin:/bin`.
Ejemplo completo: `apps/dag_engine/dags_migrated/daily-registry-audit.yaml`.
### Cron schedule
5 campos clasicos: `min hour dom mon dow`. Ejemplos:
| Expresion | Significado |
|---|---|
| `0 9 * * *` | Todos los dias a las 09:00 |
| `*/15 * * * *` | Cada 15 minutos |
| `0 */6 * * *` | Cada 6 horas en punto |
| `0 9 * * 1-5` | 09:00 lunes-viernes |
| `0 21 * * 5` | 21:00 viernes |
Multiples cron en `schedule:` -> el DAG dispara por cada uno.
---
## 4. Comandos CLI
```bash
./dag_engine run <path.yaml> # ejecuta un DAG ad-hoc
./dag_engine list [dir] # lista DAGs con schedule + ultimo status
./dag_engine status [dag_name] # historial de ejecuciones
./dag_engine validate <path.yaml> # parse + validate (no ejecuta)
./dag_engine server # arranca HTTP + WS hub + frontend embebido
```
Flags del `server`:
| Flag | Default | Que |
|---|---|---|
| `--port` | 8090 | Puerto HTTP. |
| `--dags-dir` | `apps/dag_engine/dags_migrated` (via systemd unit) | Dir scaneado para YAMLs. |
| `--db` | `dag_engine.db` | SQLite con `dag_runs` + `dag_step_results`. |
| `--scheduler` | false | Si presente, arranca cron tickers automaticamente. |
---
## 5. Que hacer si algo falla
### 5.1. El DAG no aparece en la UI
**Sintoma:** anadiste un YAML pero `GET /api/dags` no lo lista.
| Causa | Diagnostico | Fix |
|---|---|---|
| YAML invalido | `./dag_engine validate <path>` muestra el error. | Corregir segun el mensaje (campo desconocido, indentacion, type wrong). |
| Filename con extension fuera de `.yaml`/`.yml` | `ls apps/dag_engine/dags_migrated/` | Renombrar a `.yaml`. |
| El servidor apunta a otro dir | `systemctl --user cat dag_engine.service` -> ver `--dags-dir`. | Ajustar unit y `daemon-reload + restart`. |
| Cache UI antiguo | C++: pulsa `Refresh`. Web: `Ctrl+F5`. | — |
### 5.2. Validation: FAIL
`validate` muestra `parse error: ...` o `Validation: FAIL`. Causas tipicas:
| Mensaje | Causa | Fix |
|---|---|---|
| `yaml unmarshal: ...` | Sintaxis YAML rota (indentacion, tab vs espacios). | Usar 2 espacios consistentes. Validar online con `yamllint`. |
| `dag_parse: step[N]: name is required` | Step sin `name:`. | Anadir `name:`. |
| `dag_parse: step[N]: command or script required` | Step sin `command` ni `script`. | Anadir uno de los dos. |
| `cycle detected: A -> B -> A` | `depends` forma ciclo. | Romper la dependencia o convertir uno de los nodos en step distinto. |
| `unknown depends: <step>` | `depends:` referencia un step inexistente. | Comprobar nombres exactos (case-sensitive). |
| `invalid cron: <expr>` | Cron mal formado (4 o 6 campos en vez de 5). | Verificar `0 9 * * *` (5 campos). |
### 5.3. El DAG corre pero un step falla
**Sintoma:** `status: failed` en la UI.
1. Abre `DAG Detail` y haz doble-click en el run rojo -> `Run Detail`.
2. Expande el step que fallo (CollapsingHeader). Muestra `stdout` + `stderr`.
3. Errores tipicos:
| stderr | Causa | Fix |
|---|---|---|
| `command not found` | `command:` apunta a un binario fuera de `PATH`. | Path absoluto o setear `env: [PATH: ...]`. |
| `permission denied` | Script sin `chmod +x`. | `chmod +x <script>` (o usar `bash <script>`). |
| `no such file or directory` | `working_dir:` mal o ruta relativa rota. | Path absoluto en `working_dir:`. |
| Timeout | Step duro mas que `timeout_sec`. | Subir el limite o partir el step. |
| Exit 137 / OOM kill | Out-of-memory. | Reducir batch o anadir swap. |
### 5.4. El scheduler no dispara
**Sintoma:** Hay `schedule:` valido pero el DAG no corre solo.
1. Verifica que el server arranco con `--scheduler`:
```bash
systemctl --user cat dag_engine.service | grep scheduler
```
2. Logs:
```bash
journalctl --user-unit dag_engine.service -n 50 --no-pager | grep -E "scheduler|ticker"
```
Debes ver `[scheduler] ticker started for <name> (<cron>), next: <ISO8601>`.
3. Si `next:` es muy lejano (ej. en una semana) y necesitas probar -> dispara manual:
```bash
curl -X POST http://127.0.0.1:8090/api/dags/<name>/run
```
4. Hora del sistema descalibrada:
```bash
timedatectl status
```
Si difiere de la hora real, `sudo timedatectl set-ntp true`.
### 5.5. El frontend C++ no conecta WS
**Sintoma:** Panel `Live (WS)` muestra `disconnected`.
| Causa | Fix |
|---|---|
| Servidor caido | `systemctl --user status dag_engine.service`, `restart` si `inactive`. |
| Puerto cambiado | El cliente apunta a `127.0.0.1:8090` por codigo (constante `g_ws_port`). Reedificar si cambiaste el puerto del server. |
| Firewall Windows -> WSL | WSL2 expone `localhost`, normalmente OK. Si falla: `wsl --shutdown` y reabrir. |
### 5.6. Cleanup de runs viejos
`dag_runs` y `dag_step_results` crecen sin limite. Para limpiar:
```bash
sqlite3 apps/dag_engine/dag_engine.db <<'SQL'
DELETE FROM dag_step_results WHERE run_id IN (
SELECT id FROM dag_runs WHERE started_at < datetime('now', '-30 days')
);
DELETE FROM dag_runs WHERE started_at < datetime('now', '-30 days');
VACUUM;
SQL
```
### 5.7. Restaurar desde backup
Si rompes `dags_migrated/`, recupera desde el snapshot de `backup_all_bash_pipelines` (BACKUP_ROOT por defecto `~/backups/fn_registry`):
```bash
cp ~/backups/fn_registry/registry/daily.0/dags_migrated/*.yaml \
apps/dag_engine/dags_migrated/ 2>/dev/null || \
git checkout HEAD -- apps/dag_engine/dags_migrated/
systemctl --user restart dag_engine.service
```
---
## 6. Endpoints HTTP
| Metodo | Path | Que |
|---|---|---|
| GET | `/api/dags` | Lista DAGs + last_run + last_runs[5]. |
| GET | `/api/dags/{name}` | Detalle + validation. |
| POST | `/api/dags/{name}/run` | Dispara ejecucion (trigger=`api`). Devuelve `run_id`. |
| GET | `/api/runs` | Historial. Query: `dag`, `limit`, `offset`. |
| GET | `/api/runs/{id}` | Detalle de un run + sus step_results. |
| GET | `/api/ws/dagruns` | WebSocket. Snapshot + deltas en vivo (issue 0095). |
| GET | `/api/scheduler/status` | Tickers activos. |
| POST | `/api/scheduler/start` | Arranca scheduler (si no estaba). |
| POST | `/api/scheduler/stop` | Para scheduler. |
---
## 7. Referencias
- Schema parser: `functions/core/dag_parse.go` (frontmatter en `dag_parse_go_core`).
- Validator: `functions/core/dag_validate.go` (`dag_validate_go_core`).
- Topo sort: `functions/core/dag_topo_sort.go` (`dag_topo_sort_go_core`).
- Cron: `functions/core/parse_cron_expr.go` + `next_cron_time.go`.
- Frontend C++: `cpp/apps/dag_engine_ui/` (issue 0095).
- WS hub: `apps/dag_engine/events.go`.
- dag_engine es el scheduler oficial del ecosistema. Single-binary Go + SQLite, sin dependencias externas.
+9 -1
View File
@@ -6,7 +6,7 @@ import (
)
// RegisterAPI sets up all HTTP routes on the given mux.
func RegisterAPI(mux *http.ServeMux, executor *Executor, scheduler *Scheduler, frontendFS fs.FS) {
func RegisterAPI(mux *http.ServeMux, executor *Executor, scheduler *Scheduler, hub *DagRunHub, frontendFS fs.FS) {
// API routes.
mux.HandleFunc("GET /api/dags", handleListDags(executor))
mux.HandleFunc("GET /api/dags/{name}", handleGetDag(executor))
@@ -15,10 +15,18 @@ func RegisterAPI(mux *http.ServeMux, executor *Executor, scheduler *Scheduler, f
mux.HandleFunc("GET /api/runs", handleListRuns(executor))
mux.HandleFunc("GET /api/runs/{id}", handleGetRun(executor))
// Function lookup proxy a registry.db (read-only).
mux.HandleFunc("GET /api/functions/{id}", handleGetFunction())
mux.HandleFunc("POST /api/scheduler/start", handleSchedulerStart(scheduler))
mux.HandleFunc("POST /api/scheduler/stop", handleSchedulerStop(scheduler))
mux.HandleFunc("GET /api/scheduler/status", handleSchedulerStatus(scheduler))
// Live updates (WS hub).
if hub != nil {
mux.HandleFunc("GET /api/ws/dagruns", handleDagRunsWS(hub))
}
// Frontend SPA fallback.
if frontendFS != nil {
mux.Handle("/", spaHandler(frontendFS))
+65 -7
View File
@@ -2,7 +2,8 @@
name: dag_engine
lang: go
domain: infra
description: "Motor de ejecucion de DAGs con CLI y interfaz web. Reemplaza Dagu con implementacion propia compatible con el formato YAML existente. Almacena historial de ejecuciones en SQLite."
version: 0.1.0
description: "Motor de ejecucion de DAGs del fn_registry: CLI + servidor HTTP + scheduler cron. Schema YAML propio con `function:` para invocar funciones del registry (`fn run <id>`) y `command:` para shell. Historial en SQLite. Scheduler oficial del ecosistema."
tags: [service, dag, workflow, scheduler, web, cron]
uses_functions:
- dag_parse_go_core
@@ -27,6 +28,18 @@ uses_types:
framework: "net/http + vite + react"
entry_point: "main.go"
dir_path: "apps/dag_engine"
service:
port: 8090
health_endpoint: /api/dags
health_timeout_s: 3
systemd_unit: dag_engine.service
systemd_scope: user
restart_policy: always
runtime: systemd-user
pc_targets:
- aurgi-pc
- home-wsl
is_local_only: false
---
## Arquitectura
@@ -71,15 +84,60 @@ cd .. && CGO_ENABLED=1 go build -tags fts5 -o dag-engine .
```bash
# CLI
./dag-engine run ~/dagu/dags/example.yaml
./dag-engine list ~/dagu/dags/
./dag-engine run apps/dag_engine/dags_migrated/fn_backup.yaml
./dag-engine list apps/dag_engine/dags_migrated/
# Servidor web
./dag-engine server --port 8090 --dags-dir ~/dagu/dags/ --scheduler
# Servidor web (production: gestionado por dag_engine.service systemd user unit)
./dag-engine server --port 8090 --dags-dir apps/dag_engine/dags_migrated/ --scheduler
# Browser: http://localhost:8090
```
## Notas
Compatible con el formato YAML de Dagu. Lee DAGs existentes de `~/dagu/dags/` sin modificaciones.
Puerto por defecto 8090 (mismo que Dagu).
Schema YAML propio (ver `README.md` seccion 3 + ejemplos en `dags_migrated/`). Steps tipo `function:` invocan `fn run <id>` y propagan `function_id` a `dag_step_results` para el bucle reactivo. Puerto default 8090.
### 2026-05-16 — Fix function-not-found en steps `function:` + panel Logs en RunDetail `[done]`
Sintoma: `fn_backup` y `daily-registry-audit` fallaron 3 noches seguidas con `error: function "<id>" not found (tried as ID and name)` aunque las funciones existen en `registry.db` raiz.
Raiz: servicio systemd `dag_engine.service` tiene `WorkingDirectory=/home/lucas/fn_registry/apps/dag_engine`. Binario `fn` resuelve `registry.db` por (1) `FN_REGISTRY_ROOT`, (2) `root()` walk-up buscando `go.mod`, (3) exe dir (`cmd/fn/ops.go:1597-1628`). Sin `FN_REGISTRY_ROOT` seteado, (2) encuentra el `go.mod` de `apps/dag_engine/` y devuelve ese dir — donde habia una copia stale `apps/dag_engine/registry.db` (262 KB, May 15) sin las funciones recien creadas. Viola regla `.claude/rules/db_locations.md` (registry.db SOLO en raiz).
Fix:
- Borrado `apps/dag_engine/registry.db` stale.
- `~/.config/systemd/user/dag_engine.service`: anadido `Environment=FN_REGISTRY_ROOT=/home/lucas/fn_registry`, `FN_BIN=/home/lucas/fn_registry/fn`, `PATH=/usr/local/go/bin:/home/lucas/go/bin:...`, `HOME=/home/lucas`. Sin PATH el step `go vet` fallaba con `exec: "go": executable file not found in $PATH`.
- `apps/dag_engine/executor.go`: para steps `function:` el spawn exporta `FN_REGISTRY_ROOT=<root>` en env y, si `step.dir`/`working_dir` vacios, fija `dir = fnRegistryRoot`. Belt-and-suspenders: aunque alguien lance el binario sin systemd, los `function:` steps usan el root canonico.
Verificacion: `POST /api/dags/daily-registry-audit/run` -> step `audit_capabilities` pasa (387 ms) en vez de fallar con not-found. Restantes failures (`audit_artefacts` exit 1, `fn_backup` exit 4 sin respetar `continue_on.exit_code`) son bugs reales independientes — fuera de scope.
### 2026-05-16 — Panel Logs en RunDetail (frontend) `[done]`
- `apps/dag_engine/frontend/src/pages/RunDetail.tsx`: nuevo `<Paper>` "Logs" al final con `<Code block>` scrollable (max-h 480) + `CopyButton` de Mantine (icono toggle copy/check teal).
- Helper `buildLogText(run, steps)` compone texto plano: metadata del run (dag, path, status, trigger, started/finished ISO, duration ms, error) + por step (`[status] name exit=N Nms`, started, finished, error, stdout, stderr indentado 4 espacios).
- Permite pegar log entero al LLM para debugging sin abrir N collapses del `StepTimeline`.
- Build frontend pendiente: `pnpm build` rompe por errores preexistentes (`StepTimeline.tsx:49` usa API legacy `<Collapse in={opened}>`; `main.tsx:1` importa `@mantine/core/styles.css` sin tipos). Edit de RunDetail type-checkea limpio.
### 2026-05-16 — BBDDs canonicas (referencia rapida)
- `dag_engine.db`: `apps/dag_engine/dag_engine.db` (+ WAL sidecars). Migrations en `apps/dag_engine/store/migrations/` (`001_init.sql`, `002_step_function_id.sql`). Tablas `dag_runs`, `dag_step_results`.
- NO debe coexistir copia de `registry.db` en este dir (viola `db_locations.md`). Si reaparece: borrarla.
## Lo siguiente que pega
- `audit_artefacts` falla con exit 1 en `daily-registry-audit` — investigar stderr real (probablemente artefacto huerfano o git drift). Step independiente, no bloquea el resto del DAG.
- `fn_backup` step `run_backup_all` sale con exit 4 y el DAG no respeta `continue_on.exit_code: [4]`. Bug en executor: parsear `step.ContinueOn.ExitCode []int` y comparar con `result.ExitCode`. Hoy solo se mira `step.ContinueOn.Failure` (bool).
- Frontend `pnpm build` roto por API drift de Mantine en `StepTimeline.tsx` (`<Collapse in={opened}>`) y CSS type import en `main.tsx`. Fix junto con un refresh general de tipos.
## Documentacion de usuario
Guia completa (formato YAML, anadir DAGs, troubleshooting, endpoints HTTP):
**[apps/dag_engine/README.md](README.md)**.
## Capability growth log
Una linea por bump SemVer. Bump-type segun `.claude/commands/version.md`:
- `major`: breaking observable (CLI args, schema BBDD propia, formato wire).
- `minor`: feature aditiva (nuevo panel, endpoint, opcion).
- `patch`: bugfix sin cambio observable.
- v0.1.0 (2026-05-18) — baseline.
@@ -0,0 +1,26 @@
name: fn_backup
description: Backup diario de fn_registry (registry.db + operations.db + vaults) via funcion del registry
schedule:
- "0 3 * * *"
tags: [backup, registry, daily]
env:
- BACKUP_ROOT: /home/lucas/backups/fn_registry
steps:
- name: ensure_dirs
command: mkdir -p ${BACKUP_ROOT}
- name: run_backup_all
description: "Snapshot atomico de registry.db + operations.db + vaults con retention 7/4/12"
function: backup_all_bash_pipelines
args: ["${BACKUP_ROOT}"]
continue_on:
exit_code: [4]
depends: [ensure_dirs]
- name: report_status
command: bash -c 'ls -lh ${BACKUP_ROOT}/registry/daily.0 ${BACKUP_ROOT}/operations/*/daily.0 2>/dev/null | tail -20'
depends: [run_backup_all]
@@ -0,0 +1,51 @@
name: revision-viernes-finanzas
description: Revisión semanal de finanzas personales - ingesta, informe y push a Gitea
tags: [finanzas, semanal]
type: graph
schedule: "0 9 * * 5"
env:
- PROJECT_DIR: /home/lucas/analysis/finanzas_personales
- PYTHON: /home/lucas/analysis/finanzas_personales/.venv/bin/python
handler_on:
failure:
command: echo "[$(date)] FALLÓ revision-viernes-finanzas" >> /home/lucas/dagu/logs/failures.log
steps:
- id: ingest
description: Procesar archivos nuevos del inbox (BBVA xlsx + Revolut csv)
working_dir: ${PROJECT_DIR}
command: ./bin/ingest -skip-notebooks
continue_on:
failure: true
- id: informe
description: Generar informe semanal de cumplimiento del presupuesto
command: ${PYTHON} /home/lucas/dagu/scripts/informe_finanzas.py
depends: [ingest]
- id: git_push
description: Commit y push del informe a Gitea
working_dir: ${PROJECT_DIR}
script: |
#!/bin/bash
set -euo pipefail
if git diff --quiet data/04_output/informe_semanal.md 2>/dev/null && \
! git ls-files --others --exclude-standard | grep -q informe_semanal.md; then
echo "Sin cambios en el informe, skip push"
exit 0
fi
git add data/04_output/informe_semanal.md
git add data/03_processed/ 2>/dev/null || true
git commit -m "Informe semanal $(date +%Y-%m-%d)
Co-Authored-By: Dagu Automation <noreply@dagu.dev>"
git push origin master:main
echo "Push completado"
depends: [informe]
+438
View File
@@ -0,0 +1,438 @@
package main
// WebSocket hub para live updates de dag_runs + dag_step_results.
// Patron: sqlite_api/events.go (CallMonitorHub) — issue 0095.
//
// Diseño:
// - Hub global con N subscribers WS.
// - Ticker arranca solo con >=1 subscriber. Cero overhead si nadie mira.
// - Cada tick (500ms): query rowid>watermark + activos (status running/pending)
// + recientes finished (ultimos 5s) -> broadcast upsert.
// - Snapshot inicial: lista de DAGs + ultimos 50 runs + step_results.
// - El cliente trata `runs` y `steps` como upserts por id.
import (
"context"
"database/sql"
"log"
"net/http"
"sync"
"time"
"nhooyr.io/websocket"
"nhooyr.io/websocket/wsjson"
"dag-engine/store"
)
const (
dagWSTickInterval = 500 * time.Millisecond
dagWSTickIntervalIdle = 2 * time.Second
dagWSIdleThreshold = 30 * time.Second
dagWSSnapshotRuns = 50
dagWSBroadcastTimeout = 2 * time.Second
dagWSRecentFinishedS = 5
)
type wsRun struct {
ID string `json:"id"`
DagName string `json:"dag_name"`
DagPath string `json:"dag_path"`
Status string `json:"status"`
Trigger string `json:"trigger"`
StartedAt string `json:"started_at"`
FinishedAt string `json:"finished_at,omitempty"`
Error string `json:"error,omitempty"`
}
type wsStep struct {
ID string `json:"id"`
RunID string `json:"run_id"`
StepName string `json:"step_name"`
Status string `json:"status"`
ExitCode int `json:"exit_code"`
Stdout string `json:"stdout,omitempty"`
Stderr string `json:"stderr,omitempty"`
StartedAt string `json:"started_at,omitempty"`
FinishedAt string `json:"finished_at,omitempty"`
DurationMs int64 `json:"duration_ms"`
Error string `json:"error,omitempty"`
}
type wsWatermark struct {
Runs int64 `json:"runs"`
Steps int64 `json:"steps"`
}
type wsDagMessage struct {
Type string `json:"type"` // snapshot|delta|ping
Watermark wsWatermark `json:"watermark"`
Dags []DagInfo `json:"dags,omitempty"`
Runs []wsRun `json:"runs,omitempty"`
Steps []wsStep `json:"steps,omitempty"`
ServerTime int64 `json:"server_time"`
}
type wsDagClientCmd struct {
Watermark wsWatermark `json:"watermark,omitempty"`
}
type dagSubscriber struct {
conn *websocket.Conn
ctx context.Context
cancel context.CancelFunc
out chan wsDagMessage
watermark wsWatermark
}
// DagRunHub broadcastea cambios de dag_runs + dag_step_results a clientes WS.
type DagRunHub struct {
db *store.DB
executor *Executor
mu sync.Mutex
subscribers map[*dagSubscriber]struct{}
tickerStop chan struct{}
tickerOn bool
watermark wsWatermark
lastEventAt time.Time
}
func NewDagRunHub(db *store.DB, executor *Executor) *DagRunHub {
return &DagRunHub{
db: db,
executor: executor,
subscribers: make(map[*dagSubscriber]struct{}),
}
}
func (h *DagRunHub) register(s *dagSubscriber) {
h.mu.Lock()
h.subscribers[s] = struct{}{}
shouldStart := !h.tickerOn
if shouldStart {
h.tickerStop = make(chan struct{})
h.tickerOn = true
h.lastEventAt = time.Now()
}
h.mu.Unlock()
if shouldStart {
go h.tickerLoop()
}
}
func (h *DagRunHub) unregister(s *dagSubscriber) {
h.mu.Lock()
if _, ok := h.subscribers[s]; !ok {
h.mu.Unlock()
return
}
delete(h.subscribers, s)
close(s.out)
shouldStop := h.tickerOn && len(h.subscribers) == 0
if shouldStop {
close(h.tickerStop)
h.tickerOn = false
}
h.mu.Unlock()
}
func (h *DagRunHub) tickerLoop() {
interval := dagWSTickInterval
t := time.NewTimer(interval)
defer t.Stop()
for {
select {
case <-h.tickerStop:
return
case <-t.C:
runs, steps, wm, err := h.fetchDelta(h.getWatermark())
if err != nil {
log.Printf("[dagws] fetchDelta: %v", err)
} else if len(runs) > 0 || len(steps) > 0 {
h.setWatermark(wm)
h.recordActivity()
h.broadcast(wsDagMessage{
Type: "delta",
Watermark: wm,
Runs: runs,
Steps: steps,
ServerTime: time.Now().Unix(),
})
}
if time.Since(h.lastActivityAt()) > dagWSIdleThreshold {
interval = dagWSTickIntervalIdle
} else {
interval = dagWSTickInterval
}
t.Reset(interval)
}
}
}
func (h *DagRunHub) getWatermark() wsWatermark {
h.mu.Lock()
defer h.mu.Unlock()
return h.watermark
}
func (h *DagRunHub) setWatermark(v wsWatermark) {
h.mu.Lock()
if v.Runs > h.watermark.Runs {
h.watermark.Runs = v.Runs
}
if v.Steps > h.watermark.Steps {
h.watermark.Steps = v.Steps
}
h.mu.Unlock()
}
func (h *DagRunHub) recordActivity() {
h.mu.Lock()
h.lastEventAt = time.Now()
h.mu.Unlock()
}
func (h *DagRunHub) lastActivityAt() time.Time {
h.mu.Lock()
defer h.mu.Unlock()
return h.lastEventAt
}
// fetchDelta devuelve runs/steps con (rowid > watermark) OR (status in-flight)
// OR (recently finished). Watermark devuelto = max rowid visto.
func (h *DagRunHub) fetchDelta(since wsWatermark) ([]wsRun, []wsStep, wsWatermark, error) {
conn := h.db.Conn()
if conn == nil {
return nil, nil, since, nil
}
cutoff := time.Now().Add(-time.Duration(dagWSRecentFinishedS) * time.Second).Format(time.RFC3339)
runs, maxRuns, err := scanRuns(conn, `
SELECT rowid, id, dag_name, dag_path, status, trigger, started_at,
COALESCE(finished_at,''), error
FROM dag_runs
WHERE rowid > ?
OR status IN ('running','pending')
OR (finished_at IS NOT NULL AND finished_at >= ?)
ORDER BY rowid ASC`, since.Runs, cutoff)
if err != nil {
return nil, nil, since, err
}
steps, maxSteps, err := scanSteps(conn, `
SELECT rowid, id, run_id, step_name, status, exit_code, stdout, stderr,
COALESCE(started_at,''), COALESCE(finished_at,''), duration_ms, error
FROM dag_step_results
WHERE rowid > ?
OR status IN ('running','pending')
OR (finished_at IS NOT NULL AND finished_at >= ?)
ORDER BY rowid ASC`, since.Steps, cutoff)
if err != nil {
return runs, nil, since, err
}
out := wsWatermark{Runs: maxRuns, Steps: maxSteps}
if out.Runs < since.Runs {
out.Runs = since.Runs
}
if out.Steps < since.Steps {
out.Steps = since.Steps
}
return runs, steps, out, nil
}
// fetchSnapshot devuelve DAGs + ultimos N runs + sus step_results + watermark.
func (h *DagRunHub) fetchSnapshot() ([]DagInfo, []wsRun, []wsStep, wsWatermark, error) {
dags, err := h.executor.ListDAGs()
if err != nil {
log.Printf("[dagws] list dags: %v", err)
dags = nil
}
conn := h.db.Conn()
if conn == nil {
return dags, nil, nil, wsWatermark{}, nil
}
runs, maxRuns, err := scanRuns(conn, `
SELECT rowid, id, dag_name, dag_path, status, trigger, started_at,
COALESCE(finished_at,''), error
FROM dag_runs
ORDER BY started_at DESC
LIMIT ?`, dagWSSnapshotRuns)
if err != nil {
return dags, nil, nil, wsWatermark{}, err
}
steps, maxSteps, err := scanSteps(conn, `
SELECT rowid, id, run_id, step_name, status, exit_code, stdout, stderr,
COALESCE(started_at,''), COALESCE(finished_at,''), duration_ms, error
FROM dag_step_results
WHERE run_id IN (SELECT id FROM dag_runs ORDER BY started_at DESC LIMIT ?)
ORDER BY rowid ASC`, dagWSSnapshotRuns)
if err != nil {
return dags, runs, nil, wsWatermark{Runs: maxRuns}, err
}
return dags, runs, steps, wsWatermark{Runs: maxRuns, Steps: maxSteps}, nil
}
func scanRuns(conn *sql.DB, q string, args ...any) ([]wsRun, int64, error) {
rows, err := conn.Query(q, args...)
if err != nil {
return nil, 0, err
}
defer rows.Close()
var out []wsRun
var max int64
for rows.Next() {
var r wsRun
var rowid int64
if err := rows.Scan(&rowid, &r.ID, &r.DagName, &r.DagPath, &r.Status,
&r.Trigger, &r.StartedAt, &r.FinishedAt, &r.Error); err != nil {
return nil, 0, err
}
if rowid > max {
max = rowid
}
out = append(out, r)
}
return out, max, rows.Err()
}
func scanSteps(conn *sql.DB, q string, args ...any) ([]wsStep, int64, error) {
rows, err := conn.Query(q, args...)
if err != nil {
return nil, 0, err
}
defer rows.Close()
var out []wsStep
var max int64
for rows.Next() {
var s wsStep
var rowid int64
if err := rows.Scan(&rowid, &s.ID, &s.RunID, &s.StepName, &s.Status,
&s.ExitCode, &s.Stdout, &s.Stderr, &s.StartedAt, &s.FinishedAt,
&s.DurationMs, &s.Error); err != nil {
return nil, 0, err
}
if rowid > max {
max = rowid
}
out = append(out, s)
}
return out, max, rows.Err()
}
func (h *DagRunHub) broadcast(msg wsDagMessage) {
h.mu.Lock()
subs := make([]*dagSubscriber, 0, len(h.subscribers))
for s := range h.subscribers {
subs = append(subs, s)
}
h.mu.Unlock()
for _, s := range subs {
select {
case s.out <- msg:
default:
log.Printf("[dagws] dropping frame for slow subscriber")
}
}
}
// handleDagRunsWS upgrade WS y gestiona lifecycle.
// Endpoint: GET /api/ws/dagruns
func handleDagRunsWS(hub *DagRunHub) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{
InsecureSkipVerify: true,
})
if err != nil {
log.Printf("[dagws] accept: %v", err)
return
}
defer conn.Close(websocket.StatusInternalError, "closing")
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
sub := &dagSubscriber{
conn: conn,
ctx: ctx,
cancel: cancel,
out: make(chan wsDagMessage, 64),
}
hub.register(sub)
defer hub.unregister(sub)
dags, runs, steps, wm, err := hub.fetchSnapshot()
if err != nil {
log.Printf("[dagws] snapshot: %v", err)
conn.Close(websocket.StatusInternalError, "snapshot failed")
return
}
hub.setWatermark(wm)
initial := wsDagMessage{
Type: "snapshot",
Watermark: wm,
Dags: dags,
Runs: runs,
Steps: steps,
ServerTime: time.Now().Unix(),
}
if err := wsjson.Write(ctx, conn, initial); err != nil {
return
}
readErr := make(chan error, 1)
go func() {
for {
var cmd wsDagClientCmd
if err := wsjson.Read(ctx, conn, &cmd); err != nil {
readErr <- err
return
}
if cmd.Watermark.Runs > 0 || cmd.Watermark.Steps > 0 {
runs, steps, wm, err := hub.fetchDelta(cmd.Watermark)
if err == nil && (len(runs) > 0 || len(steps) > 0) {
hub.setWatermark(wm)
select {
case sub.out <- wsDagMessage{
Type: "delta",
Watermark: wm,
Runs: runs,
Steps: steps,
ServerTime: time.Now().Unix(),
}:
default:
}
}
}
}
}()
for {
select {
case <-ctx.Done():
return
case err := <-readErr:
if err != nil {
return
}
case msg, ok := <-sub.out:
if !ok {
return
}
wctx, wcancel := context.WithTimeout(ctx, dagWSBroadcastTimeout)
err := wsjson.Write(wctx, conn, msg)
wcancel()
if err != nil {
return
}
}
}
}
}
+53 -20
View File
@@ -156,22 +156,49 @@ func (e *Executor) ExecuteDAG(ctx context.Context, dagPath string, trigger strin
func (e *Executor) executeStep(ctx context.Context, runID string, dag core.DagDefinition, step core.DagStep, daguEnvPath string, outputs map[string]string, mu *sync.Mutex) error {
stepID := generateID()
now := time.Now()
// Resolve command source: function (registry) takes precedence over command/script.
var command string
var stepFunctionID string
var fnRegistryRoot string
if step.Function != "" {
stepFunctionID = step.Function
fnRegistryRoot = os.Getenv("FN_REGISTRY_ROOT")
if fnRegistryRoot == "" {
fnRegistryRoot = "/home/lucas/fn_registry"
}
fnBin := os.Getenv("FN_BIN")
if fnBin == "" {
fnBin = fnRegistryRoot + "/fn"
}
parts := []string{fnBin, "run", step.Function}
parts = append(parts, step.Args...)
command = strings.Join(parts, " ")
} else if step.Command != "" {
command = step.Command
} else if step.Script != "" {
command = step.Script
}
e.store.InsertStepResult(&store.DagStepResult{
ID: stepID,
RunID: runID,
StepName: stepName(step),
Status: "running",
StartedAt: &now,
ID: stepID,
RunID: runID,
StepName: stepName(step),
FunctionID: stepFunctionID,
Status: "running",
StartedAt: &now,
})
// Build environment.
env := buildStepEnv(dag, step, daguEnvPath, outputs)
// Determine command.
command := step.Command
if command == "" && step.Script != "" {
command = step.Script
// For function: steps, force FN_REGISTRY_ROOT into env so `fn run`
// resolves the canonical registry.db (not whatever lives at the spawn cwd).
// Prevents the apps/dag_engine/registry.db stale-shadow bug (2026-05-16).
if stepFunctionID != "" {
env = append(env, "FN_REGISTRY_ROOT="+fnRegistryRoot)
}
if command == "" {
e.store.UpdateStepResult(stepID, "skipped", 0, "", "", nil, 0, "no command or script")
return nil
@@ -182,11 +209,15 @@ func (e *Executor) executeStep(ctx context.Context, runID string, dag core.DagDe
command = resolveStepRefs(command, outputs)
mu.Unlock()
// Determine working directory.
// Determine working directory. function: steps default to FN_REGISTRY_ROOT
// so `fn` resolves registry.db correctly via go.mod walk-up.
dir := step.Dir
if dir == "" {
dir = dag.WorkingDir
}
if dir == "" && stepFunctionID != "" {
dir = fnRegistryRoot
}
shell := step.Shell
if shell == "" {
@@ -326,14 +357,15 @@ func generateID() string {
// DagInfo summarizes a DAG file for listing.
type DagInfo struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Schedule []string `json:"schedule,omitempty"`
Tags []string `json:"tags,omitempty"`
Type string `json:"type,omitempty"`
FilePath string `json:"file_path"`
Valid bool `json:"valid"`
LastRun *store.DagRun `json:"last_run,omitempty"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Schedule []string `json:"schedule,omitempty"`
Tags []string `json:"tags,omitempty"`
Type string `json:"type,omitempty"`
FilePath string `json:"file_path"`
Valid bool `json:"valid"`
LastRun *store.DagRun `json:"last_run,omitempty"`
LastRuns []store.DagRun `json:"last_runs,omitempty"` // 5 mas recientes (mas reciente primero)
}
// ListDAGs scans a directory for YAML files and returns parsed DAG info.
@@ -379,10 +411,11 @@ func (e *Executor) ListDAGs() ([]DagInfo, error) {
Valid: true,
}
// Attach last run info.
runs, _, _ := e.store.ListRuns(dag.Name, 1, 0)
// Attach last 5 runs (most recent first).
runs, _, _ := e.store.ListRuns(dag.Name, 5, 0)
if len(runs) > 0 {
info.LastRun = &runs[0]
info.LastRuns = runs
}
dags = append(dags, info)
@@ -9,12 +9,63 @@ import {
Paper,
Alert,
Loader,
CopyButton,
Tooltip,
ActionIcon,
Code,
} from "@mantine/core";
import { IconArrowLeft } from "@tabler/icons-react";
import { IconArrowLeft, IconCopy, IconCheck } from "@tabler/icons-react";
import { getRun } from "../api";
import { StatusBadge } from "../components/StatusBadge";
import { StepTimeline } from "../components/StepTimeline";
import type { RunDetail as RunDetailType } from "../types";
import type { RunDetail as RunDetailType, DagStepResult, DagRun } from "../types";
function buildLogText(run: DagRun, steps: DagStepResult[]): string {
const lines: string[] = [];
const started = run.StartedAt ? new Date(run.StartedAt) : null;
const finished = run.FinishedAt ? new Date(run.FinishedAt) : null;
const durationMs =
started && finished ? finished.getTime() - started.getTime() : null;
lines.push(`=== DAG run ${run.ID} ===`);
lines.push(`dag: ${run.DagName}`);
lines.push(`path: ${run.DagPath}`);
lines.push(`status: ${run.Status}`);
lines.push(`trigger: ${run.Trigger}`);
lines.push(`started: ${started ? started.toISOString() : "-"}`);
lines.push(`finished: ${finished ? finished.toISOString() : "-"}`);
lines.push(
`duration: ${durationMs !== null ? `${durationMs} ms` : "running..."}`
);
if (run.Error) {
lines.push("");
lines.push("run error:");
lines.push(run.Error);
}
lines.push("");
lines.push(`--- steps (${steps.length}) ---`);
for (const s of steps) {
lines.push("");
lines.push(
`[${s.Status}] ${s.StepName} exit=${s.ExitCode} ${s.DurationMs}ms`
);
if (s.StartedAt) lines.push(` started: ${s.StartedAt}`);
if (s.FinishedAt) lines.push(` finished: ${s.FinishedAt}`);
if (s.Error) {
lines.push(" error:");
lines.push(s.Error.split("\n").map((l) => " " + l).join("\n"));
}
if (s.Stdout) {
lines.push(" stdout:");
lines.push(s.Stdout.split("\n").map((l) => " " + l).join("\n"));
}
if (s.Stderr) {
lines.push(" stderr:");
lines.push(s.Stderr.split("\n").map((l) => " " + l).join("\n"));
}
}
return lines.join("\n");
}
export function RunDetail() {
const { id } = useParams<{ id: string }>();
@@ -100,6 +151,41 @@ export function RunDetail() {
</Text>
)}
</Paper>
<Paper p="md" withBorder>
<Group justify="space-between" mb="sm">
<Title order={4}>Logs</Title>
<CopyButton value={buildLogText(run, steps || [])} timeout={1500}>
{({ copied, copy }) => (
<Tooltip
label={copied ? "Copiado" : "Copiar log completo"}
withArrow
position="left"
>
<ActionIcon
variant={copied ? "filled" : "light"}
color={copied ? "teal" : "blue"}
onClick={copy}
aria-label="Copiar logs"
>
{copied ? <IconCheck size={16} /> : <IconCopy size={16} />}
</ActionIcon>
</Tooltip>
)}
</CopyButton>
</Group>
<Code
block
style={{
maxHeight: 480,
overflow: "auto",
whiteSpace: "pre",
fontSize: 12,
}}
>
{buildLogText(run, steps || [])}
</Code>
</Paper>
</Stack>
);
}
+9 -6
View File
@@ -5,6 +5,7 @@ go 1.25.0
require (
fn-registry v0.0.0-00010101000000-000000000000
github.com/mattn/go-sqlite3 v1.14.37
nhooyr.io/websocket v1.8.17
)
require (
@@ -28,19 +29,21 @@ require (
github.com/marcboeker/go-duckdb v1.8.5 // indirect
github.com/paulmach/orb v0.12.0 // indirect
github.com/pierrec/lz4/v4 v4.1.25 // indirect
github.com/rogpeppe/go-internal v1.14.1 // indirect
github.com/segmentio/asm v1.2.1 // indirect
github.com/shopspring/decimal v1.4.0 // indirect
github.com/zeebo/xxh3 v1.0.2 // indirect
go.opentelemetry.io/otel v1.41.0 // indirect
go.opentelemetry.io/otel/trace v1.41.0 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/crypto v0.50.0 // indirect
golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c // indirect
golang.org/x/mod v0.27.0 // indirect
golang.org/x/sync v0.19.0 // indirect
golang.org/x/sys v0.41.0 // indirect
golang.org/x/text v0.29.0 // indirect
golang.org/x/tools v0.36.0 // indirect
golang.org/x/mod v0.34.0 // indirect
golang.org/x/net v0.53.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.43.0 // indirect
golang.org/x/telemetry v0.0.0-20260311193753-579e4da9a98c // indirect
golang.org/x/text v0.36.0 // indirect
golang.org/x/tools v0.43.0 // indirect
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+18 -10
View File
@@ -111,44 +111,50 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI=
golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q=
golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c h1:KL/ZBHXgKGVmuZBZ01Lt57yE5ws8ZPSkkihmEyq7FXc=
golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c/go.mod h1:tujkw807nyEEAamNbDrEGzRav+ilXA7PCRAd6xsmwiU=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.27.0 h1:kb+q2PyFnEADO2IEF935ehFUXlWiNjJWtRNgBLSfbxQ=
golang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc=
golang.org/x/mod v0.34.0 h1:xIHgNUUnW6sYkcM5Jleh05DvLOtwc6RitGHbDk4akRI=
golang.org/x/mod v0.34.0/go.mod h1:ykgH52iCZe79kzLLMhyCUzhMci+nQj+0XkbXpNYtVjY=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA=
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/telemetry v0.0.0-20260311193753-579e4da9a98c h1:6a8FdnNk6bTXBjR4AGKFgUKuo+7GnR3FX5L7CbveeZc=
golang.org/x/telemetry v0.0.0-20260311193753-579e4da9a98c/go.mod h1:TpUTTEp9frx7rTdLpC9gFG9kdI7zVLFTFFlqaH2Cncw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=
golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s=
golang.org/x/tools v0.43.0 h1:12BdW9CeB3Z+J/I/wj34VMl8X+fEXBxVR90JeMX5E7s=
golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@@ -166,3 +172,5 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EV
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
nhooyr.io/websocket v1.8.17 h1:KEVeLJkUywCKVsnLIDlD/5gtayKp8VoCkksHCGGfT9Y=
nhooyr.io/websocket v1.8.17/go.mod h1:rN9OFWIUwuxg4fR5tELlYC04bXYowCP9GX47ivo2l+c=
+4 -4
View File
@@ -30,10 +30,10 @@ func handleGetDag(executor *Executor) http.HandlerFunc {
runs, _, _ := executor.store.ListRuns(dag.Name, 10, 0)
resp := map[string]interface{}{
"info": info,
"dag": dag,
"validation": validation,
"runs": runs,
"info": info,
"dag": dag,
"validation": validation,
"recent_runs": runs,
}
writeJSON(w, http.StatusOK, resp)
}
+2 -1
View File
@@ -286,6 +286,7 @@ func cmdServer(args []string) {
executor := NewExecutor(db, cfg.DagsDir)
scheduler := NewScheduler(executor, cfg.DagsDir)
dagRunHub := NewDagRunHub(db, executor)
// Prepare frontend FS.
var feFS iofs.FS
@@ -303,7 +304,7 @@ func cmdServer(args []string) {
}
mux := http.NewServeMux()
RegisterAPI(mux, executor, scheduler, feFS)
RegisterAPI(mux, executor, scheduler, dagRunHub, feFS)
handler := corsMiddleware(loggingMiddleware(mux))
+63 -28
View File
@@ -2,15 +2,43 @@ package store
import (
"database/sql"
_ "embed"
"embed"
"fmt"
"io/fs"
"sort"
"strings"
"time"
_ "github.com/mattn/go-sqlite3"
)
//go:embed migrations/001_init.sql
var migrationSQL string
//go:embed migrations/*.sql
var migrationsFS embed.FS
// applyMigrations executes every embedded migrations/*.sql in order.
// Each statement is idempotent (IF NOT EXISTS / ADD COLUMN). Duplicate-column
// errors from re-running ALTER TABLE ADD COLUMN are tolerated.
func applyMigrations(conn *sql.DB) error {
files, err := fs.Glob(migrationsFS, "migrations/*.sql")
if err != nil {
return err
}
sort.Strings(files)
for _, f := range files {
b, err := migrationsFS.ReadFile(f)
if err != nil {
return fmt.Errorf("%s: read: %w", f, err)
}
if _, err := conn.Exec(string(b)); err != nil {
if strings.Contains(err.Error(), "duplicate column") ||
strings.Contains(err.Error(), "already exists") {
continue
}
return fmt.Errorf("%s: %w", f, err)
}
}
return nil
}
// DB wraps a SQLite connection for DAG run persistence.
type DB struct {
@@ -24,7 +52,7 @@ func Open(path string) (*DB, error) {
if err != nil {
return nil, fmt.Errorf("store: open %s: %w", path, err)
}
if _, err := conn.Exec(migrationSQL); err != nil {
if err := applyMigrations(conn); err != nil {
conn.Close()
return nil, fmt.Errorf("store: migrate: %w", err)
}
@@ -36,18 +64,24 @@ func (db *DB) Close() error {
return db.conn.Close()
}
// Conn exposes the underlying *sql.DB for read-only queries from other
// packages (e.g. WS hub in events.go). Do not Close() the returned conn.
func (db *DB) Conn() *sql.DB {
return db.conn
}
// --- DagRun CRUD ---
// DagRun mirrors infra.DagRun for the store layer.
type DagRun struct {
ID string
DagName string
DagPath string
Status string
Trigger string
StartedAt time.Time
FinishedAt *time.Time
Error string
ID string `json:"id"`
DagName string `json:"dag_name"`
DagPath string `json:"dag_path"`
Status string `json:"status"`
Trigger string `json:"trigger"`
StartedAt time.Time `json:"started_at"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
Error string `json:"error,omitempty"`
}
// CreateRun inserts a new run record.
@@ -123,17 +157,18 @@ func (db *DB) ListRuns(dagName string, limit, offset int) ([]DagRun, int, error)
// DagStepResult mirrors infra.DagStepResult for the store layer.
type DagStepResult struct {
ID string
RunID string
StepName string
Status string
ExitCode int
Stdout string
Stderr string
StartedAt *time.Time
FinishedAt *time.Time
DurationMs int64
Error string
ID string `json:"id"`
RunID string `json:"run_id"`
StepName string `json:"step_name"`
FunctionID string `json:"function_id,omitempty"`
Status string `json:"status"`
ExitCode int `json:"exit_code"`
Stdout string `json:"stdout,omitempty"`
Stderr string `json:"stderr,omitempty"`
StartedAt *time.Time `json:"started_at,omitempty"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
DurationMs int64 `json:"duration_ms"`
Error string `json:"error,omitempty"`
}
// InsertStepResult inserts a new step result.
@@ -148,9 +183,9 @@ func (db *DB) InsertStepResult(r *DagStepResult) error {
finishedAt = &s
}
_, err := db.conn.Exec(
`INSERT INTO dag_step_results (id, run_id, step_name, status, exit_code, stdout, stderr, started_at, finished_at, duration_ms, error)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
r.ID, r.RunID, r.StepName, r.Status, r.ExitCode, r.Stdout, r.Stderr,
`INSERT INTO dag_step_results (id, run_id, step_name, function_id, status, exit_code, stdout, stderr, started_at, finished_at, duration_ms, error)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
r.ID, r.RunID, r.StepName, r.FunctionID, r.Status, r.ExitCode, r.Stdout, r.Stderr,
startedAt, finishedAt, r.DurationMs, r.Error,
)
return err
@@ -173,7 +208,7 @@ func (db *DB) UpdateStepResult(id, status string, exitCode int, stdout, stderr s
// ListStepResults returns all step results for a given run.
func (db *DB) ListStepResults(runID string) ([]DagStepResult, error) {
rows, err := db.conn.Query(
`SELECT id, run_id, step_name, status, exit_code, stdout, stderr, started_at, finished_at, duration_ms, error
`SELECT id, run_id, step_name, function_id, status, exit_code, stdout, stderr, started_at, finished_at, duration_ms, error
FROM dag_step_results WHERE run_id=? ORDER BY started_at ASC`, runID,
)
if err != nil {
@@ -185,7 +220,7 @@ func (db *DB) ListStepResults(runID string) ([]DagStepResult, error) {
for rows.Next() {
var r DagStepResult
var startedAt, finishedAt sql.NullString
if err := rows.Scan(&r.ID, &r.RunID, &r.StepName, &r.Status, &r.ExitCode,
if err := rows.Scan(&r.ID, &r.RunID, &r.StepName, &r.FunctionID, &r.Status, &r.ExitCode,
&r.Stdout, &r.Stderr, &startedAt, &finishedAt, &r.DurationMs, &r.Error); err != nil {
return nil, err
}
+15 -1
View File
@@ -2,6 +2,7 @@
name: shaders_lab
lang: cpp
domain: gfx
version: 0.1.0
description: "Live GLSL shader playground con DAG pipeline. Editor de codigo con compilacion en caliente, panel DAG con paleta de generadores/filtros/output, dos canvas (Code y DAG), parseo de uniforms anotados (// @slider, @color, @xy) que se convierten en controles, persistencia de generators en shaders_lab.db, y guardado/carga de layouts ImGui."
tags: [imgui, opengl, glsl, shaders, dag, live-coding, playground, sqlite]
uses_functions:
@@ -30,8 +31,11 @@ uses_types:
- dag_types_cpp_gfx
framework: "imgui"
entry_point: "main.cpp"
dir_path: "cpp/apps/shaders_lab"
dir_path: "apps/shaders_lab"
repo_url: ""
icon:
phosphor: "palette"
accent: "#ea580c"
---
## Arquitectura
@@ -102,3 +106,13 @@ cd cpp && cmake -B build/windows -S . -DCMAKE_TOOLCHAIN_FILE=toolchains/mingw-w6
- El boton "Save as generator" valida snake_case, evita colisionar con
builtins, traduce con `code_to_generator`, persiste con `shaderlab_db_save_generator`,
y registra el nodo nuevo en el catalogo en vivo (`dag_register_node`).
## Capability growth log
Una linea por bump SemVer. Bump-type segun `.claude/commands/version.md`:
- `major`: breaking observable (CLI args, schema BBDD propia, formato wire).
- `minor`: feature aditiva (nuevo panel, endpoint, opcion).
- `patch`: bugfix sin cambio observable.
- v0.1.0 (2026-05-18) — baseline.
+1 -1
View File
@@ -7,7 +7,7 @@ version: "1.0.0"
purity: impure
signature: "analyze_dns(domain: string, mode: string) -> void"
description: "Análisis DNS completo de un dominio: registros A/AAAA/MX/NS/TXT/CNAME/SOA, consulta whois y verificación contra listas negras DNSBL (spamhaus, spamcop, sorbs, barracuda)."
tags: [bash, cybersecurity, dns, network, whois, dnsbl, reconnaissance]
tags: [bash, cybersecurity, dns, network, whois, dnsbl, reconnaissance, pendiente-usar]
uses_functions: []
uses_types: []
returns: []
@@ -7,7 +7,7 @@ version: "1.0.0"
purity: impure
signature: "audit_http_headers(url: string) -> void"
description: "Audita las cabeceras HTTP de seguridad de una URL: verifica la presencia de HSTS (con validación de max-age mínimo de 6 meses), Content-Security-Policy, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, Permissions-Policy y cabeceras CORS. También detecta cabeceras que exponen información del servidor."
tags: [bash, cybersecurity, web, http, headers, security, hsts, csp, hardening]
tags: [bash, cybersecurity, web, http, headers, security, hsts, csp, hardening, pendiente-usar]
uses_functions: []
uses_types: []
returns: []
@@ -7,7 +7,7 @@ version: "1.0.0"
purity: impure
signature: "audit_ssh_config(config_path: string) -> void"
description: "Audita la configuración de sshd_config evaluando parámetros de seguridad críticos (PermitRootLogin, PasswordAuthentication, Port, MaxAuthTries, X11Forwarding, AllowUsers). También revisa intentos de login fallidos en los logs y lista las claves autorizadas del usuario actual."
tags: [bash, cybersecurity, ssh, audit, security, hardening, linux]
tags: [bash, cybersecurity, ssh, audit, security, hardening, linux, pendiente-usar]
uses_functions: []
uses_types: []
returns: []
@@ -7,7 +7,7 @@ version: "1.0.0"
purity: impure
signature: "check_firewall() -> void"
description: "Detecta el firewall activo del sistema (ufw, firewalld o iptables) y muestra su estado, reglas activas y puertos en escucha para cruzar con las reglas. Si no se detecta ningún firewall, emite una advertencia de exposición."
tags: [bash, cybersecurity, firewall, ufw, iptables, network, hardening, linux]
tags: [bash, cybersecurity, firewall, ufw, iptables, network, hardening, linux, pendiente-usar]
uses_functions: []
uses_types: []
returns: []
@@ -7,7 +7,7 @@ version: "1.0.0"
purity: impure
signature: "detect_suspicious_users() -> void"
description: "Revisa el sistema en busca de indicadores de compromiso en cuentas de usuario: UIDs 0 extras (además de root), usuarios con shell de login válida, homes en rutas inusuales, miembros de grupos privilegiados (sudo, docker, wheel, adm, etc.) y sesiones activas."
tags: [bash, cybersecurity, users, audit, linux, privilege-escalation, hardening]
tags: [bash, cybersecurity, users, audit, linux, privilege-escalation, hardening, pendiente-usar]
uses_functions: []
uses_types: []
returns: []
+1 -1
View File
@@ -7,7 +7,7 @@ version: "1.0.0"
purity: impure
signature: "encrypt_file(mode: string, file: string) -> void"
description: "Cifra o descifra un archivo usando AES-256-CBC con PBKDF2 (310.000 iteraciones) via openssl. La contraseña se lee de la variable de entorno ENCRYPT_PASSWORD o se solicita interactivamente. El archivo cifrado se guarda con extensión .enc; al descifrar se recupera el nombre original."
tags: [bash, cybersecurity, encryption, aes256, openssl, crypto, pbkdf2]
tags: [bash, cybersecurity, encryption, aes256, openssl, crypto, pbkdf2, pendiente-usar]
uses_functions: []
uses_types: []
returns: []
@@ -7,7 +7,7 @@ version: "1.0.0"
purity: impure
signature: "enumerate_subdomains(domain: string, output_file: string) -> void"
description: "Enumera subdominios de un dominio objetivo usando un diccionario integrado de ~100 subdominios comunes (www, mail, api, dev, admin, vpn, etc.). Detecta tanto registros A (IP directa) como CNAME. Muestra progreso cada 20 subdominios y opcionalmente guarda los resultados en un archivo."
tags: [bash, cybersecurity, dns, subdomain, enumeration, reconnaissance, osint]
tags: [bash, cybersecurity, dns, subdomain, enumeration, reconnaissance, osint, pendiente-usar]
uses_functions: []
uses_types: []
returns: []
@@ -7,7 +7,7 @@ version: "1.0.0"
purity: impure
signature: "generate_password(mode: string, length: int, count: int) -> void"
description: "Genera contraseñas seguras en cuatro modos: full (alfanumérico + símbolos, excluye caracteres ambiguos), alpha (solo alfanumérico), passphrase (palabras aleatorias unidas con guión) y pin (numérico). Calcula y muestra la entropía en bits para cada modo."
tags: [bash, cybersecurity, password, generator, entropy, security, urandom]
tags: [bash, cybersecurity, password, generator, entropy, security, urandom, pendiente-usar]
uses_functions: []
uses_types: []
returns: []
+1 -1
View File
@@ -7,7 +7,7 @@ version: "1.0.0"
purity: impure
signature: "geolocate_ip(target: string) -> void"
description: "Geolocaliza una dirección IP o dominio usando la API pública de ip-api.com. Muestra país, región, ciudad, coordenadas, ISP, ASN y detecta VPN, Proxy o infraestructura de hosting."
tags: [bash, cybersecurity, network, geoip, ip, osint, reconnaissance]
tags: [bash, cybersecurity, network, geoip, ip, osint, reconnaissance, pendiente-usar]
uses_functions: []
uses_types: []
returns: []
@@ -7,7 +7,7 @@ version: "1.0.0"
purity: impure
signature: "inspect_ssl_cert(host: string) -> void"
description: "Inspecciona el certificado SSL/TLS de un host: muestra sujeto, emisor, fechas de validez, días hasta expiración, SANs (Subject Alternative Names), cadena de confianza completa y detecta soporte de versiones inseguras TLS 1.0/1.1."
tags: [bash, cybersecurity, ssl, tls, certificate, web, openssl, security]
tags: [bash, cybersecurity, ssl, tls, certificate, web, openssl, security, pendiente-usar]
uses_functions: []
uses_types: []
returns: []
@@ -7,7 +7,7 @@ version: "1.0.0"
purity: impure
signature: "list_active_connections(mode: string) -> void"
description: "Muestra conexiones de red activas del sistema usando ss: puertos en escucha, conexiones establecidas y detección de conexiones hacia IPs externas (excluye RFC1918, loopback y link-local)."
tags: [bash, cybersecurity, network, connections, monitoring, ss, ports]
tags: [bash, cybersecurity, network, connections, monitoring, ss, ports, pendiente-usar]
uses_functions: []
uses_types: []
returns: []
@@ -6,16 +6,21 @@
scan_secrets_in_dirty() {
local repo_dir="${1:-.}"
if [[ ! -d "$repo_dir/.git" ]]; then
# Accept both regular repos (.git is a directory) and worktrees (.git is a
# file containing "gitdir: ..." pointer).
if [[ ! -d "$repo_dir/.git" && ! -f "$repo_dir/.git" ]]; then
echo "scan_secrets_in_dirty: '$repo_dir' no es un repo git" >&2
return 1
fi
# Listar archivos modificados o nuevos (excluyendo borrados)
# y filtrar por patron de secret en el nombre del archivo
# y filtrar por patron de secret en el nombre del archivo.
# Excluye extensiones de codigo (sh/go/py/ts/md/etc) para no marcar el
# propio scanner ni docs que hablen de "secret"/"token".
git -C "$repo_dir" status --porcelain \
| awk '{print $NF}' \
| grep -E '(^|/)(\.env(\..*)?$|.*credentials.*|.*\.key$|.*\.pem$|id_rsa.*|.*secret.*|.*token.*\.txt$)' \
| grep -Ev '\.(sh|go|py|ts|tsx|js|jsx|md|rs|cpp|h|hpp|c|java|rb|html|css)$' \
|| true
}
@@ -7,7 +7,7 @@ version: "1.0.0"
purity: impure
signature: "verify_file_hash(file: string, algorithm: string, expected_hash: string) -> void"
description: "Calcula el hash criptográfico de un archivo con el algoritmo especificado (md5, sha1, sha256, sha512) y opcionalmente lo compara con un hash esperado para verificar integridad. Retorna exit code 1 si los hashes no coinciden."
tags: [bash, cybersecurity, hash, integrity, checksum, md5, sha256, sha512]
tags: [bash, cybersecurity, hash, integrity, checksum, md5, sha256, sha512, pendiente-usar]
uses_functions: []
uses_types: []
returns: []
+98
View File
@@ -0,0 +1,98 @@
---
name: adb_wsl
kind: function
lang: bash
domain: infra
version: "1.0.0"
purity: impure
signature: "source adb_wsl.sh [ADB=<path>] [ANDROID_SDK_WIN=<sdk_root>]"
description: "Wrapper sourceable para usar adb.exe Windows desde WSL2. Resuelve binario, convierte paths, espera boot del emulador."
tags: ["android", "adb", "wsl", "windows"]
params:
- name: ADB
desc: "Env var opcional. Path absoluto a adb.exe. Si no se fija, se construye desde ANDROID_SDK_WIN o el default /mnt/c/Users/lucas/AppData/Local/Android/Sdk."
- name: ANDROID_SDK_WIN
desc: "Env var opcional. Raiz del Android SDK montado en WSL. Default: /mnt/c/Users/lucas/AppData/Local/Android/Sdk."
output: "Source-able shell helpers: adb_run, adb_devices, adb_wsl_to_win, adb_wait_boot. Define ADB env var apuntando a Windows adb.exe via ANDROID_SDK_WIN."
uses_functions: []
uses_types: []
returns: []
returns_optional: false
error_type: "error_go_core"
imports: []
tested: false
tests: []
test_file_path: ""
file_path: "bash/functions/infra/adb_wsl.sh"
---
## Uso
```bash
# Sourcear (usa SDK default)
source bash/functions/infra/adb_wsl.sh
# Sourcear con SDK custom
ANDROID_SDK_WIN=/mnt/d/Android/Sdk source bash/functions/infra/adb_wsl.sh
# Sourcear con binario fijo
ADB=/mnt/c/my/tools/adb.exe source bash/functions/infra/adb_wsl.sh
```
## Funciones expuestas
### `adb_run "<args...>"`
Ejecuta `$ADB` con los argumentos dados. Retorna el exit code de `adb.exe`.
```bash
adb_run shell ls /sdcard/
adb_run install app.apk
```
### `adb_devices`
Alias de `adb_run devices`. Lista dispositivos/emuladores conectados.
```bash
adb_devices
# List of devices attached
# emulator-5554 device
```
### `adb_wsl_to_win <path_wsl>`
Convierte un path WSL a formato Windows con `wslpath -w`. Si `wslpath` no está disponible retorna el path sin convertir.
```bash
win_path=$(adb_wsl_to_win /home/lucas/proyecto/app.apk)
# C:\Users\lucas\AppData\Local\... (o la ruta Windows equivalente)
adb_run install "$win_path"
```
### `adb_wait_boot [timeout_s]`
Espera a que el emulador/dispositivo complete el boot (`sys.boot_completed = 1`). Útil tras lanzar un AVD en CI.
```bash
adb_wait_boot # timeout 120s
adb_wait_boot 60 # timeout 60s
```
Retorna `0` si el boot se completó, `1` si expiró el timeout.
## Smoke test
```bash
bash bash/functions/infra/adb_wsl.sh --self-test
# OK
```
## Notas
- El script es **source-able**: define funciones en el shell actual, no crea subshell.
- `ADB` se resuelve una sola vez al sourcing. Si el binario no existe en disco, la carga falla con mensaje en stderr y `return 1` / `exit 1`.
- `adb_wait_boot` hace polling cada 3 segundos. Ajustar `interval` si el emulador es especialmente lento.
- En WSL2 `wslpath` siempre está disponible; el fallback existe para entornos Linux puros que accidentalmente sourceen el archivo.
- Si el emulador requiere `-s <serial>`, pasar el flag directamente a `adb_run`: `adb_run -s emulator-5554 shell ...`.
---
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env bash
# adb_wsl — Wrapper sourceable para usar adb.exe Windows desde WSL2.
# Uso: source bash/functions/infra/adb_wsl.sh
# Smoke test: bash bash/functions/infra/adb_wsl.sh --self-test
# ---------------------------------------------------------------------------
# Resolver ADB
# ---------------------------------------------------------------------------
# El caller puede fijar ADB antes de sourcing para apuntar a otro binario.
if [[ -z "${ADB:-}" ]]; then
_sdk_root="${ANDROID_SDK_WIN:-/mnt/c/Users/lucas/AppData/Local/Android/Sdk}"
ADB="${_sdk_root}/platform-tools/adb.exe"
unset _sdk_root
fi
if [[ ! -f "$ADB" ]]; then
echo "adb_wsl: ADB no encontrado en '$ADB'. Fija ADB= o ANDROID_SDK_WIN= antes de sourcear." >&2
# Solo abortamos si el script se ejecuta directamente; si se sourcea,
# permitimos continuar para que el caller maneje el error.
return 1 2>/dev/null || exit 1
fi
# ---------------------------------------------------------------------------
# adb_run "<args...>"
# Ejecuta el ADB Windows con los argumentos dados.
# Retorna el exit code de adb.exe.
# ---------------------------------------------------------------------------
adb_run() {
"$ADB" "$@"
}
# ---------------------------------------------------------------------------
# adb_devices
# Lista dispositivos ADB conectados.
# ---------------------------------------------------------------------------
adb_devices() {
adb_run devices
}
# ---------------------------------------------------------------------------
# adb_wsl_to_win <path_wsl>
# Convierte un path WSL a formato Windows usando wslpath.
# Si wslpath no está disponible retorna el path tal cual.
# ---------------------------------------------------------------------------
adb_wsl_to_win() {
local path_wsl="$1"
if command -v wslpath &>/dev/null; then
wslpath -w "$path_wsl"
else
echo "$path_wsl"
fi
}
# ---------------------------------------------------------------------------
# adb_wait_boot [timeout_s]
# Espera a que el dispositivo/emulador complete el boot (sys.boot_completed=1).
# timeout_s: segundos máximos de espera (default 120).
# Retorna 0 si boot completado, 1 si timeout.
# ---------------------------------------------------------------------------
adb_wait_boot() {
local timeout_s="${1:-120}"
local elapsed=0
local interval=3
while (( elapsed < timeout_s )); do
local val
val=$(adb_run shell getprop sys.boot_completed 2>/dev/null | tr -d '[:space:]')
if [[ "$val" == "1" ]]; then
return 0
fi
sleep "$interval"
(( elapsed += interval ))
done
echo "adb_wsl: timeout ${timeout_s}s esperando boot del dispositivo." >&2
return 1
}
# ---------------------------------------------------------------------------
# adb_pick_serial [--serial <S>] [...]
# Resuelve el serial a usar para multi-device. Lee --serial X de los args.
# Setea globals ADB_PICK_SERIAL y ADB_PICK_REST (no usa stdout para evitar
# perder los globals via subshell de $()).
# Exit 1 si no hay device disponible.
#
# Uso tipico:
# adb_pick_serial "$@" || { echo "no device" >&2; exit 3; }
# local serial="$ADB_PICK_SERIAL"
# set -- "${ADB_PICK_REST[@]}"
# ---------------------------------------------------------------------------
adb_pick_serial() {
ADB_PICK_SERIAL="${ADB_SERIAL:-}"
ADB_PICK_REST=()
while [[ $# -gt 0 ]]; do
case "$1" in
--serial) ADB_PICK_SERIAL="$2"; shift 2 ;;
--serial=*) ADB_PICK_SERIAL="${1#--serial=}"; shift ;;
*) ADB_PICK_REST+=("$1"); shift ;;
esac
done
if [[ -z "$ADB_PICK_SERIAL" ]]; then
ADB_PICK_SERIAL=$(adb_run devices 2>/dev/null | awk '/(emulator-|device$)/ && !/List of/ {print $1; exit}')
fi
if [[ -z "$ADB_PICK_SERIAL" ]]; then
echo "adb_wsl: ningun device/emulador conectado." >&2
return 1
fi
if ! adb_run devices 2>/dev/null | awk '{print $1}' | grep -qx "$ADB_PICK_SERIAL"; then
echo "adb_wsl: serial '$ADB_PICK_SERIAL' no encontrado en adb devices." >&2
return 1
fi
return 0
}
# ---------------------------------------------------------------------------
# adb_s <serial> <args...>
# Atajo: adb_run -s <serial> <args...>
# ---------------------------------------------------------------------------
adb_s() {
local serial="$1"; shift
adb_run -s "$serial" "$@"
}
# ---------------------------------------------------------------------------
# Smoke test (solo si invocado directamente con --self-test)
# ---------------------------------------------------------------------------
if [[ "${1:-}" == "--self-test" ]]; then
adb_run version || exit 1
echo "OK"
fi
+1 -1
View File
@@ -7,7 +7,7 @@ version: "1.0.0"
purity: impure
signature: "analyze_disk_space([target_dir: string], [mode: string]) -> void"
description: "Analiza el uso de espacio en disco. Modos: partitions (df con filtros), top-dirs (du top 10), top-files (find top 20), inodes (df -i), all (todos). Emite advertencias si el uso supera el 90%."
tags: [bash, disk, space, analysis, filesystem]
tags: [bash, disk, space, analysis, filesystem, pendiente-usar]
uses_functions: []
uses_types: []
returns: []
@@ -0,0 +1,66 @@
---
name: android_apk_install
kind: function
lang: bash
domain: infra
version: "1.0.0"
purity: impure
signature: "android_apk_install([--serial S], apk_path: string, package_name?: string, activity_name?: string) -> void"
description: "Instala APK en device/emulador via adb y opcionalmente lanza la app. Multi-emulator via --serial."
tags: [android, adb, apk, wsl]
params:
- name: "--serial <S>"
desc: "Optional target device/emulator serial. Default: first device detected by adb_pick_serial."
- name: apk_path
desc: "WSL path to APK file"
- name: package_name
desc: "Optional app package id (e.g. com.fnregistry.voiceguide). Launches the app if provided."
- name: activity_name
desc: "Optional activity (.MainActivity or fully qualified). Only used with package_name. If omitted, launches via monkey LAUNCHER intent."
output: "Stdout con pasos. Exit 0 = install + launch OK. Exit !=0 si install fallo o APK no encontrado."
uses_functions: ["adb_wsl_bash_infra"]
uses_types: []
returns: []
returns_optional: false
error_type: "error_go_core"
imports: []
tested: false
tests: []
test_file_path: ""
file_path: "bash/functions/infra/android_apk_install.sh"
---
## Ejemplo
```bash
# Solo instalar
android_apk_install /home/lucas/builds/app-debug.apk
# Instalar y lanzar con activity explícita
android_apk_install /home/lucas/builds/app-debug.apk com.fnregistry.voiceguide .MainActivity
# Instalar y lanzar sin activity (usa monkey LAUNCHER)
android_apk_install /home/lucas/builds/app-debug.apk com.fnregistry.voiceguide
# Llamada directa desde shell (no sourced)
bash bash/functions/infra/android_apk_install.sh /path/to/app.apk com.example.app .MainActivity
# Override ADB path
ADB=/custom/path/adb.exe bash bash/functions/infra/android_apk_install.sh /path/to/app.apk
```
## Notas
- Requiere WSL2 con `adb.exe` Windows accesible. El path por defecto es
`/mnt/c/Users/lucas/AppData/Local/Android/Sdk/platform-tools/adb.exe`.
Se puede sobreescribir con `ADB=...` o `ANDROID_SDK_WIN=<sdk_root>` antes
de invocar.
- `wslpath` se usa para convertir el path WSL a formato Windows (`C:\...`).
Si no está disponible (entorno no-WSL), se usa el path tal cual.
- La instalación usa `adb install -r` (reinstala si ya existe).
- Si `package_name` se da sin `activity_name`, la app se lanza via
`adb shell monkey -p <pkg> -c android.intent.category.LAUNCHER 1`,
que es equivalente a pulsar el icono del launcher.
- El script se puede sourcear (para usar la función en otros scripts) o
ejecutar directamente. Cuando se ejecuta directamente, delega en
`android_apk_install "$@"`.
@@ -0,0 +1,55 @@
#!/usr/bin/env bash
# android_apk_install — Instala APK en device/emulador via adb y opcionalmente lanza la app.
# Multi-emulator via --serial <S>.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Source helpers (adb_run, adb_pick_serial, adb_s, adb_wsl_to_win)
# shellcheck source=/dev/null
source "$SCRIPT_DIR/adb_wsl.sh"
# ---------------------------------------------------------------------------
# android_apk_install [--serial <S>] <apk_path> [package_name] [activity_name]
# ---------------------------------------------------------------------------
android_apk_install() {
local serial
adb_pick_serial "$@" || { echo "android_apk_install: no device/emulator." >&2; return 3; }
local serial="$ADB_PICK_SERIAL"
set -- "${ADB_PICK_REST[@]}"
local apk="${1:-}"
local package="${2:-}"
local activity="${3:-}"
if [[ -z "$apk" ]]; then
echo "android_apk_install: se requiere apk_path como primer argumento." >&2
return 1
fi
if [[ ! -f "$apk" ]]; then
echo "android_apk_install: APK no encontrado en '$apk'." >&2
return 1
fi
local win_path
win_path=$(adb_wsl_to_win "$apk")
echo "android_apk_install: instalando '$win_path' on $serial ..."
adb_s "$serial" install -r "$win_path"
echo "android_apk_install: instalacion completada."
if [[ -n "$package" ]]; then
if [[ -n "$activity" ]]; then
echo "android_apk_install: lanzando $package/$activity ..."
adb_s "$serial" shell am start -n "$package/$activity"
else
echo "android_apk_install: lanzando $package via monkey LAUNCHER ..."
adb_s "$serial" shell monkey -p "$package" -c android.intent.category.LAUNCHER 1
fi
echo "android_apk_install: app lanzada."
fi
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
android_apk_install "$@"
fi
+52
View File
@@ -0,0 +1,52 @@
---
name: android_app_clear
kind: function
lang: bash
domain: infra
version: "1.0.0"
purity: impure
signature: "android_app_clear([--serial <S>], package: string) -> void"
description: "Wipe app data + cache via pm clear. App keeps installed but factory-state. Multi-emulator via --serial."
tags: [android, adb, app, clear, reset, pendiente-usar]
params:
- name: "--serial <S>"
desc: "Optional target device/emulator serial. Auto-detected if omitted."
- name: package
desc: "App package whose data to clear (e.g. com.example.app)."
output: "Stdout 'cleared data for <pkg> on <serial>'. Exit 0 si pm clear OK."
uses_functions: ["adb_wsl_bash_infra"]
uses_types: []
returns: []
returns_optional: false
error_type: "error_go_core"
imports: []
tested: false
tests: []
test_file_path: ""
file_path: "bash/functions/infra/android_app_clear.sh"
---
## Ejemplo
```bash
# Limpiar datos de una app (autodetecta device)
android_app_clear com.example.myapp
# Con serial explícito
android_app_clear --serial emulator-5554 com.example.myapp
# Llamada directa
bash bash/functions/infra/android_app_clear.sh com.example.myapp
bash bash/functions/infra/android_app_clear.sh --serial emulator-5554 com.example.myapp
```
## Notas
- Usa `pm clear` internamente — borra SharedPreferences, bases de datos internas,
caché y archivos de la app. La app queda como recién instalada.
- El source de `adb_wsl.sh` resuelve el binario `adb.exe` Windows desde WSL2.
Se puede sobreescribir con `ADB=...` o `ANDROID_SDK_WIN=<sdk_root>` antes de invocar.
- `adb_pick_serial` consume `--serial <S>` de los args y deja el resto en
`ADB_PICK_REST`. Si no se da, autodetecta el primer device/emulador activo.
- Exit 3 si no hay ningún device conectado (propagado desde `adb_pick_serial`).
- Exit 1 si no se pasa package.
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env bash
# android_app_clear — Wipe app data + cache via pm clear. App stays installed.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./adb_wsl.sh
source "$SCRIPT_DIR/adb_wsl.sh"
# ---------------------------------------------------------------------------
# android_app_clear [--serial <S>] <package>
#
# --serial <S> Optional target device/emulator serial.
# package App package whose data+cache to clear (e.g. com.example.app).
#
# Calls: adb shell pm clear <package>
# The app remains installed but is reset to factory state (no data, no cache).
# Exit 0 on success, exit 1 on bad args, exit 3 if no device found.
# ---------------------------------------------------------------------------
android_app_clear() {
adb_pick_serial "$@" || exit 3
local serial="$ADB_PICK_SERIAL"
set -- "${ADB_PICK_REST[@]}"
local pkg="${1:-}"
if [[ -z "$pkg" ]]; then
echo "android_app_clear: se requiere <package> como argumento." >&2
return 1
fi
adb_s "$serial" shell pm clear "$pkg"
echo "cleared data for $pkg on $serial"
}
# Run directly if not sourced
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
android_app_clear "$@"
fi
+57
View File
@@ -0,0 +1,57 @@
---
name: android_app_info
kind: function
lang: bash
domain: infra
version: "1.0.0"
purity: impure
signature: "android_app_info([--serial <S>], package, [--json]) -> stdout"
description: "Inspect installed app: version, target SDK, activities via dumpsys package."
tags: [android, adb, app, info, dumpsys, pendiente-usar]
params:
- name: "--serial <S>"
desc: "Optional ADB serial to target a specific device/emulator. Auto-detected if omitted."
- name: "package"
desc: "Android package name to inspect (e.g. com.example.myapp)."
- name: "--json"
desc: "Emit parsed JSON with versionName, versionCode, targetSdk, launcherActivity instead of raw dumpsys output."
output: "Raw dumpsys package output, or JSON object {package, versionName, versionCode, targetSdk, launcherActivity}. Outputs JSON null if package not installed (--json mode). Exit 2 if package not found in raw mode, exit 3 if no device."
uses_functions: [adb_wsl_bash_infra]
uses_types: []
returns: []
returns_optional: false
error_type: "error_go_core"
imports: []
tested: false
tests: []
test_file_path: ""
file_path: "bash/functions/infra/android_app_info.sh"
---
## Ejemplo
```bash
# Raw dumpsys (full output)
source bash/functions/infra/android_app_info.sh
android_app_info com.example.myapp
# Target specific device
android_app_info --serial emulator-5554 com.example.myapp
# Parsed JSON
android_app_info com.example.myapp --json
# {"package":"com.example.myapp","versionName":"2.1.0","versionCode":210,"targetSdk":34,"launcherActivity":"com.example.myapp/.MainActivity"}
# Package not installed → JSON null
android_app_info com.not.installed --json
# null
```
## Notas
- Sources `adb_wsl.sh` para resolver el binario ADB Windows desde WSL2 y las helpers `adb_pick_serial` / `adb_s`.
- `--serial` se consume via `adb_pick_serial`; el resto de los args quedan en `ADB_PICK_REST` y se re-asignan con `set --`.
- JSON parsing usa `grep`/`sed`/`awk` sobre la salida de `dumpsys package`. Campos faltantes se emiten como string vacío o 0; no se usa `jq` para no requerir dependencias externas.
- `launcherActivity` se extrae buscando el bloque `android.intent.action.MAIN` / `android.intent.category.LAUNCHER` en el listado de intent filters.
- Exit codes: 0 = OK, 1 = arg/adb error, 2 = package not found (raw mode), 3 = no device.
---
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env bash
# android_app_info — Inspect installed app via dumpsys package.
# Usage: android_app_info [--serial <S>] <package> [--json]
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/adb_wsl.sh"
android_app_info() {
# Resolve serial (consumes --serial from args, leaves rest in ADB_PICK_REST)
adb_pick_serial "$@" || exit 3
local serial="$ADB_PICK_SERIAL"
set -- "${ADB_PICK_REST[@]}"
# Parse remaining args: package + --json flag
local pkg=""
local want_json=0
while [[ $# -gt 0 ]]; do
case "$1" in
--json) want_json=1; shift ;;
-*) echo "android_app_info: unknown flag '$1'" >&2; return 1 ;;
*)
if [[ -z "$pkg" ]]; then
pkg="$1"
else
echo "android_app_info: unexpected argument '$1'" >&2
return 1
fi
shift ;;
esac
done
if [[ -z "$pkg" ]]; then
echo "android_app_info: package argument required" >&2
return 1
fi
local dump
dump=$(adb_s "$serial" shell dumpsys package "$pkg" 2>&1)
local rc=$?
if [[ $rc -ne 0 ]]; then
echo "android_app_info: adb dumpsys failed (exit $rc)" >&2
return 1
fi
# If dumpsys returns nothing meaningful for the package, treat as not installed
if ! echo "$dump" | grep -q "Package \["; then
if [[ $want_json -eq 1 ]]; then
echo "null"
else
echo "android_app_info: package '$pkg' not found on device" >&2
return 2
fi
return 0
fi
if [[ $want_json -eq 0 ]]; then
echo "$dump"
return 0
fi
# --- JSON extraction ---
local versionName versionCode targetSdk launcherActivity
versionName=$(echo "$dump" | grep -m1 'versionName=' \
| sed 's/.*versionName=\([^ ]*\).*/\1/')
versionCode=$(echo "$dump" | grep -m1 'versionCode=' \
| sed 's/.*versionCode=\([0-9]*\).*/\1/')
targetSdk=$(echo "$dump" | grep -m1 'targetSdk=' \
| sed 's/.*targetSdk=\([0-9]*\).*/\1/')
# Primary/launcher activity: look for MAIN/LAUNCHER category block
launcherActivity=$(echo "$dump" | awk '
/android.intent.action.MAIN/ { found=1 }
found && /[a-zA-Z0-9_.]+\/[a-zA-Z0-9_.]+/ {
match($0, /[a-zA-Z0-9_.]+\/[a-zA-Z0-9_.]+/)
print substr($0, RSTART, RLENGTH)
exit
}
')
# Emit JSON, quoting strings safely
printf '{"package":"%s","versionName":"%s","versionCode":%s,"targetSdk":%s,"launcherActivity":"%s"}\n' \
"$pkg" \
"${versionName:-}" \
"${versionCode:-0}" \
"${targetSdk:-0}" \
"${launcherActivity:-}"
}
# Run if invoked directly
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
android_app_info "$@"
fi
+44
View File
@@ -0,0 +1,44 @@
---
name: android_app_kill
kind: function
lang: bash
domain: infra
version: "1.0.0"
purity: impure
signature: "android_app_kill([--serial <S>], package: string) -> void"
description: "Force-stop running app via am force-stop. Multi-emulator via --serial."
tags: [android, adb, app, kill, force-stop, pendiente-usar]
params:
- name: "--serial <S>"
desc: "Optional target device/emulator serial. Auto-detected if omitted."
- name: "package"
desc: "App package to force-stop (e.g. com.example.myapp)."
output: "Stdout 'killed <pkg> on <serial>'. Exit 0."
uses_functions: [adb_wsl_bash_infra]
uses_types: []
returns: []
returns_optional: false
error_type: "error_go_core"
imports: []
tested: false
tests: []
test_file_path: ""
file_path: "bash/functions/infra/android_app_kill.sh"
---
## Ejemplo
```bash
# Detener app en el emulador activo
android_app_kill com.example.myapp
# Detener app en un dispositivo concreto
android_app_kill --serial emulator-5554 com.example.myapp
```
## Notas
Usa `adb_pick_serial` de `adb_wsl.sh` para resolver el dispositivo objetivo.
Si `--serial` no se pasa, autodetecta el primer device/emulador disponible.
Sale con exit 3 si no hay ningun device conectado.
`am force-stop` detiene todos los procesos y servicios de la app de forma inmediata.
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
# android_app_kill — Force-stop a running Android app via am force-stop.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=adb_wsl.sh
source "$SCRIPT_DIR/adb_wsl.sh"
android_app_kill() {
local serial pkg
adb_pick_serial "$@" || exit 3
local serial="$ADB_PICK_SERIAL"
set -- "${ADB_PICK_REST[@]}"
pkg="${1:?android_app_kill: package name required}"
adb_s "$serial" shell am force-stop "$pkg"
echo "killed $pkg on $serial"
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
android_app_kill "$@"
fi
@@ -0,0 +1,49 @@
---
name: android_app_launch
kind: function
lang: bash
domain: infra
version: "1.0.0"
purity: impure
signature: "android_app_launch([--serial <S>], package: string, [activity: string]) -> void"
description: "Launch app activity via am start. Multi-emulator via --serial."
tags: [android, adb, app, launch, activity, pendiente-usar]
params:
- name: "--serial <S>"
desc: "Optional target serial. Default: first device"
- name: "package"
desc: "App package id"
- name: "activity"
desc: "Optional activity. If omitted, launches via LAUNCHER intent"
output: "Stdout 'launched <pkg> on <serial>'. Exit 0 ok, 3 no device."
uses_functions: [adb_wsl_bash_infra]
uses_types: []
returns: []
returns_optional: false
error_type: "error_go_core"
imports: []
tested: false
tests: []
test_file_path: ""
file_path: "bash/functions/infra/android_app_launch.sh"
---
## Ejemplo
```bash
# Lanzar actividad principal explicitamente
android_app_launch com.foo.bar .MainActivity
# Lanzar por LAUNCHER intent (detecta actividad principal automaticamente)
android_app_launch com.foo.bar
# Multi-emulador: elegir serial concreto
android_app_launch --serial emulator-5554 com.foo.bar .MainActivity
```
## Notas
Usa `adb_pick_serial` de `adb_wsl.sh` para resolver el serial objetivo.
Si no hay ningun device/emulador disponible, sale con exit code 3.
Si `activity` no se especifica, usa `monkey -p <pkg> -c android.intent.category.LAUNCHER 1`
para lanzar la actividad principal sin necesidad de conocerla de antemano.
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
# android_app_launch — Launch an Android app via adb am start or monkey LAUNCHER intent.
# Usage: android_app_launch [--serial <S>] <package> [<activity>]
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/adb_wsl.sh"
android_app_launch() {
adb_pick_serial "$@" || exit 3
local serial="$ADB_PICK_SERIAL"
set -- "${ADB_PICK_REST[@]}"
local pkg="${1:-}"
local activity="${2:-}"
if [[ -z "$pkg" ]]; then
echo "android_app_launch: package is required." >&2
return 1
fi
if [[ -n "$activity" ]]; then
adb_s "$serial" shell am start -n "$pkg/$activity"
else
adb_s "$serial" shell monkey -p "$pkg" -c android.intent.category.LAUNCHER 1
fi
echo "launched $pkg on $serial"
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
android_app_launch "$@"
fi
@@ -0,0 +1,52 @@
---
name: android_app_uninstall
kind: function
lang: bash
domain: infra
version: "1.0.0"
purity: impure
signature: "android_app_uninstall([--serial <S>] package [--keep-data]) -> void"
description: "Uninstall app via adb uninstall. Optionally keep data with --keep-data."
tags: [android, adb, app, uninstall, pendiente-usar]
params:
- name: "--serial <S>"
desc: "Optional target device/emulator serial. Auto-detects first connected device if omitted."
- name: "package"
desc: "Android package name to uninstall (e.g. com.example.myapp). Mandatory positional argument."
- name: "--keep-data"
desc: "Keep app data + cache after uninstall (passes -k to pm uninstall)."
output: "Stdout 'uninstalled <pkg> on <serial>'. Exit 0 OK."
uses_functions: [adb_wsl_bash_infra]
uses_types: []
returns: []
returns_optional: false
error_type: "error_go_core"
imports: []
tested: false
tests: []
test_file_path: ""
file_path: "bash/functions/infra/android_app_uninstall.sh"
---
## Ejemplo
```bash
# Desinstalar en el device por defecto
android_app_uninstall com.example.myapp
# Desinstalar en un device concreto
android_app_uninstall --serial emulator-5554 com.example.myapp
# Desinstalar conservando datos y cache
android_app_uninstall --serial emulator-5554 com.example.myapp --keep-data
```
## Notas
Sourcea `adb_wsl.sh` para resolver el binario `adb.exe` en WSL2 y usar
`adb_pick_serial` / `adb_s`. Si no hay ningún device conectado y no se
pasa `--serial`, la función falla con exit 1 antes de invocar adb.
El flag `--keep-data` pasa `-k` a `adb uninstall`, equivalente a
`pm uninstall -k` — el APK se elimina pero los datos y la caché de la app
permanecen en el dispositivo.
@@ -0,0 +1,42 @@
#!/usr/bin/env bash
# android_app_uninstall — Desinstala una app Android via adb uninstall.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/adb_wsl.sh"
android_app_uninstall() {
# Parse --serial (consumes it, rest stays in ADB_PICK_REST)
local serial
adb_pick_serial "$@" || return 1
local serial="$ADB_PICK_SERIAL"
set -- "${ADB_PICK_REST[@]}"
# Parse --keep-data flag
local keep_data=0
local args=()
while [[ $# -gt 0 ]]; do
case "$1" in
--keep-data) keep_data=1; shift ;;
*) args+=("$1"); shift ;;
esac
done
set -- "${args[@]}"
local pkg="${1:-}"
if [[ -z "$pkg" ]]; then
echo "android_app_uninstall: package obligatorio." >&2
return 1
fi
if (( keep_data )); then
adb_s "$serial" uninstall -k "$pkg" || return 1
else
adb_s "$serial" uninstall "$pkg" || return 1
fi
echo "uninstalled $pkg on $serial"
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
android_app_uninstall "$@"
fi
@@ -0,0 +1,51 @@
---
name: android_emu_battery
kind: function
lang: bash
domain: infra
version: "1.0.0"
purity: impure
signature: "android_emu_battery([--serial <S>], level: int, [--charging <true|false>]) -> void"
description: "Simulate battery state on emulator (level + charging). Emulator-only."
tags: [android, emulator, battery, power, pendiente-usar]
params:
- name: "--serial <S>"
desc: "Optional emulator serial (e.g. emulator-5554). Auto-detected if omitted."
- name: "level"
desc: "Battery level 0-100 to set via 'emu power capacity'."
- name: "--charging <true|false>"
desc: "AC charging state: true maps to 'on', false maps to 'off'. Omit to leave unchanged."
output: "Stdout 'battery: <N>% [charging=...] on <serial>'. Exit 3 if no device found, exit 1 on other errors."
uses_functions: [adb_wsl_bash_infra]
uses_types: []
returns: []
returns_optional: false
error_type: "error_go_core"
imports: []
tested: false
tests: []
test_file_path: ""
file_path: "bash/functions/infra/android_emu_battery.sh"
notes: "Util para tests bateria baja, modo ahorro energia. Solo funciona con emuladores (serial emulator-*), no con devices fisicos."
---
## Ejemplo
```bash
# Nivel al 15%, sin cambiar estado de carga
android_emu_battery 15
# Nivel al 5%, forzar descarga (AC off)
android_emu_battery 5 --charging false
# Nivel al 80%, forzar carga (AC on), emulador concreto
android_emu_battery --serial emulator-5554 80 --charging true
```
## Notas
Util para tests de bateria baja y modo ahorro de energia. Solo funciona con emuladores Android
(serial debe empezar con `emulator-`). No aplica a dispositivos fisicos.
Requiere que `adb_wsl.sh` este en el mismo directorio. El ADB se resuelve via
`ANDROID_SDK_WIN` o la ruta por defecto de la instalacion Windows SDK.
@@ -0,0 +1,87 @@
#!/usr/bin/env bash
# android_emu_battery — Simulate battery state on Android emulator (level + charging).
# Usage: android_emu_battery [--serial <S>] <level 0-100> [--charging <true|false>]
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/adb_wsl.sh"
android_emu_battery() {
# Resolve serial (consumes --serial from args, leaves rest in ADB_PICK_REST)
adb_pick_serial "$@" || exit 3
local serial="$ADB_PICK_SERIAL"
set -- "${ADB_PICK_REST[@]}"
# Require serial to be an emulator
if [[ "$serial" != emulator-* ]]; then
echo "android_emu_battery: serial '$serial' is not an emulator (must start with emulator-)." >&2
return 1
fi
# Parse remaining args: positional level + --charging
local level=""
local charging=""
while [[ $# -gt 0 ]]; do
case "$1" in
--charging)
charging="$2"
shift 2
;;
--charging=*)
charging="${1#--charging=}"
shift
;;
-*)
echo "android_emu_battery: unknown flag '$1'." >&2
return 1
;;
*)
if [[ -z "$level" ]]; then
level="$1"
fi
shift
;;
esac
done
# Validate level
if [[ -z "$level" ]]; then
echo "android_emu_battery: level is required (0-100)." >&2
return 1
fi
if ! [[ "$level" =~ ^[0-9]+$ ]] || (( level < 0 || level > 100 )); then
echo "android_emu_battery: invalid level '$level' — must be integer 0-100." >&2
return 1
fi
# Set battery level
adb_s "$serial" emu power capacity "$level" || {
echo "android_emu_battery: failed to set capacity on $serial." >&2
return 1
}
# Set charging state if requested
local ch="<unchanged>"
if [[ -n "$charging" ]]; then
local ac_val
case "$charging" in
true) ac_val="on" ;;
false) ac_val="off" ;;
*)
echo "android_emu_battery: --charging must be 'true' or 'false', got '$charging'." >&2
return 1
;;
esac
adb_s "$serial" emu power ac "$ac_val" || {
echo "android_emu_battery: failed to set AC charging on $serial." >&2
return 1
}
ch="$charging"
fi
echo "battery: ${level}% [charging=${ch}] on ${serial}"
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
android_emu_battery "$@"
fi
@@ -0,0 +1,53 @@
---
name: android_emu_geo_fix
kind: function
lang: bash
domain: infra
version: "1.0.0"
purity: impure
signature: "android_emu_geo_fix([--serial <S>], longitude: string, latitude: string, [altitude: string]) -> void"
description: "Fake GPS location on Android emulator via emu geo fix. Emulator-only (not physical devices)."
tags: [android, emulator, geo, gps, location, pendiente-usar]
params:
- name: "--serial <S>"
desc: "Optional emulator serial. Auto-detected if omitted."
- name: "longitude"
desc: "Longitude (decimal degrees). Passed first — opposite to human lat/lon convention."
- name: "latitude"
desc: "Latitude (decimal degrees)."
- name: "altitude"
desc: "Optional altitude in meters."
output: "Stdout 'GPS set: <lon>, <lat> (alt=...) on <serial>'. Exit 0."
uses_functions: [adb_wsl_bash_infra]
uses_types: []
returns: []
returns_optional: false
error_type: "error_go_core"
imports: []
tested: false
tests: []
test_file_path: ""
file_path: "bash/functions/infra/android_emu_geo_fix.sh"
---
## Ejemplo
```bash
# Fijar GPS en Madrid (emulador activo)
android_emu_geo_fix -3.7038 40.4168
# Con altitud
android_emu_geo_fix -3.7038 40.4168 650
# Emulador especifico
android_emu_geo_fix --serial emulator-5554 -3.7038 40.4168
```
## Notas
El orden de argumentos es **longitud primero, latitud segundo** — opuesto a la convencion humana habitual (lat/lon). Esto sigue el protocolo del comando `emu geo fix` de Android.
Solo funciona en emuladores (`emulator-*`). Si el serial apunta a un dispositivo fisico, la funcion sale con error y exit 1.
Usa `adb_pick_serial` de `adb_wsl.sh` para resolver el dispositivo objetivo.
Sale con exit 3 si no hay ningun device conectado.
@@ -0,0 +1,37 @@
#!/usr/bin/env bash
# android_emu_geo_fix — Fake GPS location on Android emulator via emu geo fix.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=adb_wsl.sh
source "$SCRIPT_DIR/adb_wsl.sh"
android_emu_geo_fix() {
local serial lon lat alt
adb_pick_serial "$@" || exit 3
local serial="$ADB_PICK_SERIAL"
set -- "${ADB_PICK_REST[@]}"
lon="${1:?android_emu_geo_fix: longitude required}"
lat="${2:?android_emu_geo_fix: latitude required}"
alt="${3:-}"
# geo fix only works on emulators, not physical devices
if [[ "$serial" != emulator-* ]]; then
echo "android_emu_geo_fix: geo fix only works on emulators (got '$serial')" >&2
return 1
fi
adb_s "$serial" emu geo fix "$lon" "$lat" ${alt:+"$alt"}
if [[ -n "$alt" ]]; then
echo "GPS set: $lon, $lat (alt=$alt) on $serial"
else
echo "GPS set: $lon, $lat on $serial"
fi
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
android_emu_geo_fix "$@"
fi
@@ -0,0 +1,49 @@
---
name: android_emu_rotate
kind: function
lang: bash
domain: infra
version: "1.0.0"
purity: impure
signature: "android_emu_rotate([--serial <S>] [portrait|landscape|0|90|180|270])"
description: "Rotate emulator screen. Empty=toggle, or fixed orientation. Locks autorotate."
tags: [android, emulator, rotation, orientation, pendiente-usar]
uses_functions: [adb_wsl_bash_infra]
uses_types: []
returns: []
returns_optional: false
error_type: "error_go_core"
imports: []
params:
- name: "--serial <S>"
desc: "Optional emulator serial. Picked automatically if only one is connected."
- name: "orientation"
desc: "Empty=toggle via emu rotate, or fixed: portrait/landscape/0/90/180/270."
output: "Stdout 'rotated: <orient> on <serial>'."
tested: false
tests: []
test_file_path: ""
file_path: "bash/functions/infra/android_emu_rotate.sh"
---
## Ejemplo
```bash
# Toggle rotation
android_emu_rotate
# Force portrait
android_emu_rotate portrait
# Force landscape on specific emulator
android_emu_rotate --serial emulator-5554 landscape
# Set 270 degrees
android_emu_rotate --serial emulator-5554 270
```
## Notas
Deshabilita autorotate (`accelerometer_rotation 0`) antes de aplicar cualquier orientacion fija, de modo que el sistema no la revierta. El toggle (`emu rotate`) no desactiva autorotate: lo usa directamente el daemon del emulador.
`adb_pick_serial` (de `adb_wsl_bash_infra`) selecciona el unico emulador conectado o falla con exit 3 si hay ambiguedad o ninguno disponible. Los argumentos restantes tras extraer `--serial` quedan en `ADB_PICK_REST`.
@@ -0,0 +1,53 @@
#!/usr/bin/env bash
# android_emu_rotate — rotate emulator screen or toggle rotation
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./adb_wsl.sh
source "$SCRIPT_DIR/adb_wsl.sh"
android_emu_rotate() {
adb_pick_serial "$@" || exit 3
local serial="$ADB_PICK_SERIAL"
set -- "${ADB_PICK_REST[@]}"
local arg="${1:-}"
# Disable autorotate before any operation
if [[ -n "$arg" ]]; then
adb_s "$serial" shell settings put system accelerometer_rotation 0
fi
case "$arg" in
"")
# Toggle via emu rotate command
adb_s "$serial" emu rotate
;;
portrait|0)
adb_s "$serial" shell settings put system accelerometer_rotation 0
adb_s "$serial" shell settings put system user_rotation 0
;;
landscape|90)
adb_s "$serial" shell settings put system accelerometer_rotation 0
adb_s "$serial" shell settings put system user_rotation 1
;;
180)
adb_s "$serial" shell settings put system accelerometer_rotation 0
adb_s "$serial" shell settings put system user_rotation 2
;;
270)
adb_s "$serial" shell settings put system accelerometer_rotation 0
adb_s "$serial" shell settings put system user_rotation 3
;;
*)
echo "android_emu_rotate: unknown orientation '$arg'" >&2
echo "Usage: android_emu_rotate [--serial <S>] [portrait|landscape|0|90|180|270]" >&2
return 1
;;
esac
echo "rotated: ${arg:-toggle} on $serial"
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
android_emu_rotate "$@"
fi
@@ -0,0 +1,51 @@
---
name: android_emulator_list
kind: function
lang: bash
domain: infra
version: "1.0.0"
purity: impure
signature: "android_emulator_list([--json])"
description: "Lista los AVDs disponibles invocando emulator.exe Windows desde WSL2."
tags: [android, emulator, wsl]
uses_functions: []
uses_types: []
returns: []
returns_optional: false
error_type: "error_go_core"
imports: []
params:
- name: "--json"
desc: "Optional flag, outputs JSON array instead of newline-separated names"
output: "Lista de AVDs disponibles en el SDK Windows. Una por linea, o JSON array con --json."
tested: false
tests: []
test_file_path: ""
file_path: "bash/functions/infra/android_emulator_list.sh"
notes: "Lee env var EMULATOR o ANDROID_SDK_WIN. Default Windows path: /mnt/c/Users/lucas/AppData/Local/Android/Sdk/emulator/emulator.exe. Exit 0 si lista (incluso vacia). Exit 1 solo si el binario no existe o no es ejecutable."
---
## Ejemplo
```bash
# Listar AVDs (una por linea)
android_emulator_list
# Listar AVDs en formato JSON
android_emulator_list --json
# ["Pixel_7_API_34","Pixel_4_API_30"]
# Sobreescribir ruta del emulador
EMULATOR="/custom/path/emulator.exe" android_emulator_list
# Sobreescribir SDK base
ANDROID_SDK_WIN="/mnt/d/Android/Sdk" android_emulator_list
```
## Notas
El script es ejecutable directamente (`chmod +x`) o invocable con `bash android_emulator_list.sh`.
`emulator.exe -list-avds` imprime warnings a stderr que se descartan con `2>/dev/null`. La captura con `mapfile` filtra ademas lineas vacias para producir una lista limpia.
La variable `EMULATOR` tiene prioridad sobre `ANDROID_SDK_WIN`. Si ninguna esta definida se usa el path Windows por defecto de Lucas.
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env bash
# android_emulator_list — Lista los AVDs disponibles invocando emulator.exe Windows desde WSL2.
set -euo pipefail
# Resolve emulator binary
EMULATOR="${EMULATOR:-${ANDROID_SDK_WIN:-/mnt/c/Users/lucas/AppData/Local/Android/Sdk}/emulator/emulator.exe}"
if [[ ! -x "$EMULATOR" ]]; then
echo "error: emulator binary not found or not executable: $EMULATOR" >&2
exit 1
fi
# Parse flags
JSON=false
for arg in "$@"; do
case "$arg" in
--json) JSON=true ;;
*) echo "error: unknown argument: $arg" >&2; exit 1 ;;
esac
done
# Collect AVDs, stripping any warnings emulator.exe prints to stderr
mapfile -t AVDS < <("$EMULATOR" -list-avds 2>/dev/null || true)
if $JSON; then
# Build JSON array
printf '['
first=true
for avd in "${AVDS[@]}"; do
[[ -z "$avd" ]] && continue
if $first; then
printf '"%s"' "$avd"
first=false
else
printf ',"%s"' "$avd"
fi
done
printf ']\n'
else
for avd in "${AVDS[@]}"; do
[[ -z "$avd" ]] && continue
printf '%s\n' "$avd"
done
fi
@@ -0,0 +1,49 @@
---
name: android_emulator_start
kind: function
lang: bash
domain: infra
version: "1.0.0"
purity: impure
signature: "android_emulator_start(avd_name: string, timeout_s: int) -> string"
description: "Arranca un AVD en background y espera a que termine de bootear. Idempotente: si ya hay emulador corriendo no lanza otro."
tags: [android, emulator, wsl]
params:
- name: avd_name
desc: "Nombre del AVD a arrancar (visible con android_emulator_list o `emulator.exe -list-avds`)"
- name: timeout_s
desc: "Timeout total en segundos para esperar el boot completo. Opcional, default 180"
output: "Serial del device emulado (ej. emulator-5554) en stdout. Exit 0 = boot completo, exit 1 = timeout o emulador murio."
uses_functions: ["adb_wsl_bash_infra"]
uses_types: []
returns: []
returns_optional: false
error_type: "error_go_core"
imports: []
tested: false
tests: []
test_file_path: ""
file_path: "bash/functions/infra/android_emulator_start.sh"
---
## Ejemplo
```bash
source bash/functions/infra/android_emulator_start.sh
# Arrancar AVD con timeout por defecto (180s)
serial=$(android_emulator_start "Pixel_6_API_34")
echo "Emulador listo: $serial" # emulator-5554
# Con timeout personalizado
serial=$(android_emulator_start "Pixel_6_API_34" 300)
```
## Notas
- Sourcea `adb_wsl.sh` del mismo directorio si existe (provee `ADB`, `adb_run`, `adb_wait_boot`). Si no, usa implementacion inline.
- Resuelve `EMULATOR` y `ADB` desde `ANDROID_SDK_WIN` (default `/mnt/c/Users/lucas/AppData/Local/Android/Sdk`) o desde las variables de entorno `EMULATOR=` / `ADB=` si ya están fijadas.
- Idempotente: si `adb devices` ya muestra un `emulator-*`, imprime "already running" + el serial y sale con exit 0 sin lanzar un segundo proceso.
- Log del emulador en `/tmp/emulator_<avd>.log`. PID en `/tmp/emulator_<avd>.pid`.
- El timeout total se reparte: primera mitad para `adb wait-for-device`, segunda mitad para esperar `sys.boot_completed=1`.
- Diseñado para WSL2 con Android SDK instalado en Windows. En Linux nativo basta cambiar las rutas de los binarios via `EMULATOR=` y `ADB=`.
@@ -0,0 +1,110 @@
#!/usr/bin/env bash
# android_emulator_start — Arranca un AVD en background y espera a que bootee.
# Uso: android_emulator_start <avd_name> [timeout_s]
set -euo pipefail
# ---------------------------------------------------------------------------
# Source adb_wsl si está disponible (provee ADB, adb_run, adb_wait_boot)
# ---------------------------------------------------------------------------
_ADB_WSL_SH="$(dirname "${BASH_SOURCE[0]}")/adb_wsl.sh"
if [[ -f "$_ADB_WSL_SH" ]]; then
# shellcheck source=adb_wsl.sh
source "$_ADB_WSL_SH"
else
# Fallback inline: resolver ADB
if [[ -z "${ADB:-}" ]]; then
_sdk_root="${ANDROID_SDK_WIN:-/mnt/c/Users/lucas/AppData/Local/Android/Sdk}"
ADB="${_sdk_root}/platform-tools/adb.exe"
unset _sdk_root
fi
adb_run() { "$ADB" "$@"; }
adb_wait_boot() {
local timeout_s="${1:-120}"
local elapsed=0 interval=3 val
while (( elapsed < timeout_s )); do
val=$(adb_run shell getprop sys.boot_completed 2>/dev/null | tr -d '[:space:]')
[[ "$val" == "1" ]] && return 0
sleep "$interval"
(( elapsed += interval ))
done
echo "android_emulator_start: timeout ${timeout_s}s esperando boot." >&2
return 1
}
fi
# ---------------------------------------------------------------------------
# Resolver EMULATOR
# ---------------------------------------------------------------------------
if [[ -z "${EMULATOR:-}" ]]; then
_sdk_root="${ANDROID_SDK_WIN:-/mnt/c/Users/lucas/AppData/Local/Android/Sdk}"
EMULATOR="${_sdk_root}/emulator/emulator.exe"
unset _sdk_root
fi
# ---------------------------------------------------------------------------
# android_emulator_start <avd_name> [timeout_s]
# ---------------------------------------------------------------------------
android_emulator_start() {
local AVD="${1:?android_emulator_start requiere el nombre del AVD como primer argumento}"
local timeout_s="${2:-180}"
# Validaciones de entorno
if [[ ! -f "$EMULATOR" ]]; then
echo "android_emulator_start: emulator.exe no encontrado en '$EMULATOR'. Fija EMULATOR= o ANDROID_SDK_WIN=." >&2
return 1
fi
if [[ ! -f "$ADB" ]]; then
echo "android_emulator_start: adb.exe no encontrado en '$ADB'. Fija ADB= o ANDROID_SDK_WIN=." >&2
return 1
fi
# Idempotencia: si ya hay un emulador corriendo, salir sin lanzar otro
if adb_run devices 2>/dev/null | grep -q "emulator-"; then
echo "already running"
# Imprimir el serial existente
adb_run devices 2>/dev/null | grep "emulator-" | awk '{print $1}' | head -n1
return 0
fi
local log_file="/tmp/emulator_${AVD}.log"
local pid_file="/tmp/emulator_${AVD}.pid"
# Lanzar emulador en background
"$EMULATOR" -avd "$AVD" -no-boot-anim -no-snapshot-load >"$log_file" 2>&1 &
local emu_pid=$!
echo "$emu_pid" > "$pid_file"
# Esperar a que el dispositivo aparezca en adb
local wait_timeout=$(( timeout_s / 2 ))
if ! timeout "$wait_timeout" adb_run wait-for-device 2>/dev/null; then
echo "android_emulator_start: timeout esperando que el dispositivo aparezca en adb (${wait_timeout}s)." >&2
return 1
fi
# Verificar que el proceso del emulador sigue vivo
if ! kill -0 "$emu_pid" 2>/dev/null; then
echo "android_emulator_start: el proceso del emulador (PID $emu_pid) murió antes de completar el boot." >&2
echo " Log: $log_file" >&2
return 1
fi
# Esperar boot completo (sys.boot_completed=1)
local boot_timeout=$(( timeout_s - wait_timeout ))
if ! adb_wait_boot "$boot_timeout"; then
echo "android_emulator_start: timeout ${timeout_s}s esperando boot completo del AVD '$AVD'." >&2
echo " Log: $log_file" >&2
return 1
fi
# Obtener serial del dispositivo emulado
local serial
serial=$(adb_run devices 2>/dev/null | grep "emulator-" | awk '{print $1}' | head -n1)
echo "$serial"
return 0
}
# Ejecutar si se invoca directamente (no sourceado)
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
android_emulator_start "$@"
fi
@@ -0,0 +1,44 @@
---
name: android_emulator_stop
kind: function
lang: bash
domain: infra
version: "1.0.0"
purity: impure
signature: "android_emulator_stop(serial?: string) -> void"
description: "Para uno o todos los emuladores Android via adb emu kill. Si serial esta vacio, detecta todos los emulator-* activos y los para. Idempotente: exit 0 aunque no haya nada que matar."
tags: ["android", "emulator", "wsl", "adb"]
params:
- name: "serial"
desc: "Optional emulator serial (e.g. emulator-5554). Empty = kill all running emulators"
output: "Imprime numero de emuladores parados. Exit 0 idempotente."
uses_functions: ["adb_wsl_bash_infra"]
uses_types: []
returns: []
returns_optional: false
error_type: "error_go_core"
imports: []
tested: false
tests: []
test_file_path: ""
file_path: "bash/functions/infra/android_emulator_stop.sh"
---
## Ejemplo
```bash
# Parar todos los emuladores en ejecucion
android_emulator_stop
# Parar un emulador concreto
android_emulator_stop emulator-5554
# Sobreescribir ruta de adb
ADB=/usr/local/bin/adb android_emulator_stop
```
## Notas
Resuelve `ADB` desde variable de entorno (default: ruta de Android SDK en Windows bajo WSL2).
Usa `adb emu kill` en vez de `adb kill-server` para parar solo el emulador sin afectar al daemon adb.
`set -euo pipefail` activo, pero los fallos de `adb emu kill` se suprimen con `|| true` para mantener idempotencia.
@@ -0,0 +1,39 @@
#!/usr/bin/env bash
# android_emulator_stop — Para uno o todos los emuladores Android via adb emu kill.
set -euo pipefail
android_emulator_stop() {
local serial="${1:-}"
local ADB="${ADB:-/mnt/c/Users/lucas/AppData/Local/Android/Sdk/platform-tools/adb.exe}"
local killed=0
if [[ -z "$serial" ]]; then
# Detectar todos los emuladores activos
local serials
serials=$("$ADB" devices 2>/dev/null | grep -E '^emulator-' | awk '{print $1}' || true)
if [[ -z "$serials" ]]; then
echo "android_emulator_stop: no running emulators found"
return 0
fi
while IFS= read -r s; do
[[ -z "$s" ]] && continue
echo "android_emulator_stop: stopping $s"
"$ADB" -s "$s" emu kill 2>/dev/null || true
((killed++)) || true
done <<< "$serials"
else
echo "android_emulator_stop: stopping $serial"
"$ADB" -s "$serial" emu kill 2>/dev/null || true
((killed++)) || true
fi
echo "android_emulator_stop: stopped $killed emulator(s)"
return 0
}
# Ejecutar si se llama directamente
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
android_emulator_stop "${1:-}"
fi
@@ -0,0 +1,63 @@
---
name: android_input_keyevent
kind: function
lang: bash
domain: infra
version: "1.0.0"
purity: impure
signature: "android_input_keyevent([--serial <S>] key: string)"
description: "Send key event via adb shell input keyevent. Accepts aliases (BACK, HOME, POWER, ENTER, MENU, RECENT_APPS, VOLUME_UP, VOLUME_DOWN), raw numeric codes, or explicit KEYCODE_* names."
tags: [android, adb, input, keyevent, ui-test, pendiente-usar]
params:
- name: "--serial <S>"
desc: "Optional target device/emulator serial. If omitted, adb_pick_serial resolves the single connected device."
- name: "key"
desc: "Keycode: short alias (BACK/HOME/POWER/ENTER/MENU/RECENT_APPS/VOLUME_UP/VOLUME_DOWN), raw number (e.g. 4, 26), or explicit KEYCODE_* name."
output: "Stdout 'key: <code> on <serial>'."
uses_functions: ["adb_wsl_bash_infra"]
uses_types: []
returns: []
returns_optional: false
error_type: "error_go_core"
imports: []
tested: false
tests: []
test_file_path: ""
file_path: "bash/functions/infra/android_input_keyevent.sh"
notes: "Lista completa de keycodes: https://developer.android.com/reference/android/view/KeyEvent. Exit 3 si adb_pick_serial falla (ningun device o ambiguo sin --serial)."
---
## Ejemplo
```bash
# Pulsar BACK en el unico device conectado
android_input_keyevent BACK
# Pulsar HOME en un emulador especifico
android_input_keyevent --serial emulator-5554 HOME
# Codigo numerico directo
android_input_keyevent 26 # POWER
# KEYCODE_* explicito
android_input_keyevent KEYCODE_DPAD_CENTER
```
## Notas
Aliases resueltos internamente:
| Alias | KEYCODE |
|--------------|-----------------------|
| BACK | KEYCODE_BACK |
| HOME | KEYCODE_HOME |
| POWER | KEYCODE_POWER |
| ENTER | KEYCODE_ENTER |
| MENU | KEYCODE_MENU |
| RECENT_APPS | KEYCODE_APP_SWITCH |
| VOLUME_UP | KEYCODE_VOLUME_UP |
| VOLUME_DOWN | KEYCODE_VOLUME_DOWN |
Si el argumento no coincide con ningun alias y no es numerico, se construye `KEYCODE_<UPPER>` para pasarlo directo a `adb shell input keyevent`.
Exit codes: 1 = keycode vacio, 3 = fallo de `adb_pick_serial` (ningun device o ambiguo).
@@ -0,0 +1,50 @@
#!/usr/bin/env bash
# android_input_keyevent — Send key event via adb shell input keyevent.
# Accepts aliases (BACK, HOME, POWER, ENTER, MENU, RECENT_APPS),
# raw numeric codes, or explicit KEYCODE_* names.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=adb_wsl.sh
source "$SCRIPT_DIR/adb_wsl.sh"
android_input_keyevent() {
# Resolve serial (consumes --serial <S> from args, remainder in ADB_PICK_REST)
adb_pick_serial "$@" || exit 3
local serial="$ADB_PICK_SERIAL"
set -- "${ADB_PICK_REST[@]}"
local raw="${1:-}"
if [[ -z "$raw" ]]; then
echo "android_input_keyevent: missing keycode argument" >&2
return 1
fi
# Resolve alias → KEYCODE_*
local keycode
case "${raw^^}" in
BACK) keycode="KEYCODE_BACK" ;;
HOME) keycode="KEYCODE_HOME" ;;
POWER) keycode="KEYCODE_POWER" ;;
ENTER) keycode="KEYCODE_ENTER" ;;
MENU) keycode="KEYCODE_MENU" ;;
RECENT_APPS) keycode="KEYCODE_APP_SWITCH" ;;
VOLUME_UP) keycode="KEYCODE_VOLUME_UP" ;;
VOLUME_DOWN) keycode="KEYCODE_VOLUME_DOWN" ;;
*)
# Already has KEYCODE_ prefix or is a raw number → pass through
if [[ "${raw^^}" == KEYCODE_* ]] || [[ "$raw" =~ ^[0-9]+$ ]]; then
keycode="$raw"
else
# Unknown alias: uppercase and prepend KEYCODE_
keycode="KEYCODE_${raw^^}"
fi
;;
esac
adb_s "$serial" shell input keyevent "$keycode"
echo "key: $keycode on $serial"
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
android_input_keyevent "$@"
fi
@@ -0,0 +1,59 @@
---
name: android_input_swipe
kind: function
lang: bash
domain: infra
version: "1.0.0"
purity: impure
signature: "android_input_swipe([--serial <S>], x1: int, y1: int, x2: int, y2: int, [duration_ms: int])"
description: "Send swipe gesture between two points with duration."
tags: [android, adb, input, swipe, gesture, ui-test, pendiente-usar]
uses_functions: [adb_wsl_bash_infra]
uses_types: []
returns: []
returns_optional: false
error_type: "error_go_core"
imports: []
params:
- name: "--serial <S>"
desc: "Optional target device serial. Overrides ADB_SERIAL envvar."
- name: x1
desc: "Start X coordinate in pixels."
- name: y1
desc: "Start Y coordinate in pixels."
- name: x2
desc: "End X coordinate in pixels."
- name: y2
desc: "End Y coordinate in pixels."
- name: duration_ms
desc: "Optional swipe duration in milliseconds. Default 300."
output: "Stdout swipe summary line: 'swipe x1,y1 → x2,y2 (Nms) on <serial>'."
tested: false
tests: []
test_file_path: ""
file_path: "bash/functions/infra/android_input_swipe.sh"
---
## Ejemplo
```bash
source bash/functions/infra/android_input_swipe.sh
# Scroll down (swipe up)
android_input_swipe 540 1400 540 400
# Scroll up slowly on a specific device
android_input_swipe --serial emulator-5554 540 400 540 1400 800
```
## Notas
Requiere `adb_wsl.sh` (sourceado automáticamente). Usa `adb_pick_serial` para
resolver el dispositivo objetivo a partir de `--serial`, `ADB_SERIAL` o el
único device disponible.
Los cuatro argumentos de coordenadas se validan como enteros antes de invocar
adb — acepta coordenadas negativas (edge cases de hardware con ejes invertidos).
Exit 3 si `adb_pick_serial` no puede resolver el serial (sin devices o ambiguo).
Exit 1 si faltan coordenadas o alguna no es numérica.
@@ -0,0 +1,52 @@
#!/usr/bin/env bash
# android_input_swipe — Send swipe gesture between two points via adb shell input swipe.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=adb_wsl.sh
source "$SCRIPT_DIR/adb_wsl.sh"
# ---------------------------------------------------------------------------
# android_input_swipe [--serial <S>] <x1> <y1> <x2> <y2> [duration_ms]
#
# $1 x1 Start X coordinate in pixels (obligatorio).
# $2 y1 Start Y coordinate in pixels (obligatorio).
# $3 x2 End X coordinate in pixels (obligatorio).
# $4 y2 End Y coordinate in pixels (obligatorio).
# $5 duration_ms Swipe duration in milliseconds (opcional, default 300).
#
# Envvar ADB_SERIAL overrides --serial.
# ---------------------------------------------------------------------------
android_input_swipe() {
adb_pick_serial "$@" || exit 3
local serial="$ADB_PICK_SERIAL"
set -- "${ADB_PICK_REST[@]}"
local x1="${1:-}"
local y1="${2:-}"
local x2="${3:-}"
local y2="${4:-}"
local dur="${5:-300}"
if [[ -z "$x1" || -z "$y1" || -z "$x2" || -z "$y2" ]]; then
echo "android_input_swipe: se requieren cuatro argumentos: x1 y1 x2 y2." >&2
return 1
fi
# Validar que los cuatro coordenadas son numericas (enteros o negativos).
local coord
for coord in "$x1" "$y1" "$x2" "$y2"; do
if ! [[ "$coord" =~ ^-?[0-9]+$ ]]; then
echo "android_input_swipe: coordenada no numerica: '$coord'." >&2
return 1
fi
done
adb_s "$serial" shell input swipe "$x1" "$y1" "$x2" "$y2" "$dur"
echo "swipe $x1,$y1$x2,$y2 (${dur}ms) on $serial"
}
# Ejecutar si se llama directamente (no sourceado)
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
android_input_swipe "$@"
fi

Some files were not shown because too many files have changed in this diff Show More