@polymorphism-tech/morph-spec 8.2.1 → 8.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +73 -102
  2. package/bin/morph-spec.js +36 -1
  3. package/claude-plugin.json +1 -1
  4. package/docs/CHEATSHEET.md +77 -134
  5. package/docs/QUICKSTART.md +47 -57
  6. package/framework/CLAUDE.md +6 -3
  7. package/framework/MORPH.md +2 -2
  8. package/framework/agents.json +3 -1
  9. package/framework/commands/morph-hotfix.md +1 -1
  10. package/framework/hooks/README.md +3 -0
  11. package/framework/hooks/claude-code/core/state-sync.js +41 -9
  12. package/framework/hooks/claude-code/core/telemetry-log.js +102 -0
  13. package/framework/hooks/shared/state-writer.js +14 -3
  14. package/framework/hooks/shared/telemetry-logger.js +75 -0
  15. package/framework/rules/ai-agents-standards.md +1 -0
  16. package/framework/schemas/feature.schema.json +15 -7
  17. package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
  18. package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
  19. package/framework/skills/core/morph-apply/SKILL.md +1 -1
  20. package/framework/skills/core/morph-brainstorming/SKILL.md +1 -1
  21. package/framework/skills/core/morph-eval/SKILL.md +1 -1
  22. package/framework/skills/core/morph-hotfix/SKILL.md +3 -3
  23. package/framework/skills/core/morph-implement/SKILL.md +1 -1
  24. package/framework/skills/core/morph-plan/SKILL.md +1 -1
  25. package/framework/skills/core/morph-proposal/SKILL.md +4 -4
  26. package/framework/skills/core/morph-review/SKILL.md +1 -1
  27. package/framework/skills/core/morph-stack-scan/SKILL.md +1 -1
  28. package/framework/skills/core/morph-standards/SKILL.md +1 -1
  29. package/framework/standards/STANDARDS.json +43 -1
  30. package/framework/standards/ai-agents/observability-patterns.md +156 -0
  31. package/framework/standards/ai-agents/production.md +3 -47
  32. package/framework/templates/REGISTRY.json +0 -93
  33. package/package.json +1 -1
  34. package/src/commands/observability/telemetry.js +75 -0
  35. package/src/commands/project/doctor.js +28 -0
  36. package/src/commands/state/advance.js +17 -0
  37. package/src/commands/state/approve.js +13 -0
  38. package/src/commands/state/create.js +21 -1
  39. package/src/commands/state/delete.js +143 -0
  40. package/src/commands/state/list.js +110 -0
  41. package/src/core/state/feature-identity.js +36 -0
  42. package/src/core/state/gate-order.js +51 -0
  43. package/src/core/state/lifecycle-audit.js +79 -0
  44. package/src/core/state/state-manager.js +47 -140
  45. package/src/dashboard/app/pages/LiveState.jsx +0 -43
  46. package/src/lib/detectors/design-system-detector.js +0 -43
  47. package/src/lib/generators/index.js +0 -1
  48. package/src/lib/telemetry/telemetry-reader.js +103 -0
  49. package/src/lib/validators/validation-runner.js +9 -73
  50. package/src/utils/hooks-installer.js +27 -3
  51. package/framework/templates/context/CONTEXT-FEATURE.md +0 -269
  52. package/framework/templates/context/CONTEXT.md +0 -181
  53. package/src/lib/agents/metrics-aggregator.js +0 -56
  54. package/src/lib/agents/metrics-calculator.js +0 -125
  55. package/src/lib/generators/metadata-extractor.js +0 -385
@@ -0,0 +1,156 @@
1
+ # Observability Patterns — OpenTelemetry, enrichment, investigation
2
+
3
+ > **Scope:** stacks=["dotnet"]
4
+ > **Layer:** 1 (on-keyword)
5
+ > **Keywords:** observability, telemetry, opentelemetry, logging, tracing, log investigation, troubleshooting, aspire dashboard, span, correlation id
6
+ > **Read by Claude in:** implement (wiring telemetry into an agent) and troubleshoot (investigating a production issue)
7
+
8
+ **Verified against:** MAF 1.0 GA. Last-verified: 2026-07-22.
9
+
10
+ ---
11
+
12
+ ## Por que isso importa
13
+
14
+ Um agente MAF em produção não é uma função — é uma cadeia (LLM call → tool call → sub-agent → RAG/DB) que pode ter qualquer profundidade. Sem telemetria estruturada, um bug em produção ("o agente respondeu errado", "a automação não disparou") é indistinguível de uma caixa-preta: não dá pra saber qual chamada falhou, quanto cada etapa levou, ou qual tool retornou o quê. Este standard cobre as três partes do problema: **como instrumentar** (setup), **o que registrar** (enrichment) e **como investigar** (análise) — nessa ordem, porque setup sem enrichment produz traces vazios, e enrichment sem prática de investigação não ajuda ninguém no momento do incidente.
15
+
16
+ ---
17
+
18
+ ## Setup — OpenTelemetry
19
+
20
+ ```csharp
21
+ using OpenTelemetry;
22
+ using OpenTelemetry.Trace;
23
+ using OpenTelemetry.Metrics;
24
+ using Microsoft.Agents.AI;
25
+
26
+ // Habilitar em agents individuais
27
+ agent.WithOpenTelemetry();
28
+
29
+ // Program.cs — setup completo
30
+ builder.Services.AddOpenTelemetry()
31
+ .WithTracing(tracing =>
32
+ {
33
+ tracing.AddSource(AgentOpenTelemetryConsts.DefaultSourceName); // MAF 1.0 GA source
34
+ tracing.AddSource(builder.Environment.ApplicationName); // seus spans customizados (ver Enrichment)
35
+ tracing.AddAspNetCoreInstrumentation();
36
+ tracing.AddHttpClientInstrumentation();
37
+ tracing.AddOtlpExporter();
38
+ })
39
+ .WithMetrics(metrics =>
40
+ {
41
+ metrics.AddMeter(AgentOpenTelemetryConsts.DefaultSourceName);
42
+ metrics.AddAspNetCoreInstrumentation();
43
+ metrics.AddHttpClientInstrumentation();
44
+ metrics.AddRuntimeInstrumentation();
45
+ });
46
+
47
+ builder.Logging.AddOpenTelemetry(logging =>
48
+ {
49
+ logging.IncludeFormattedMessage = true;
50
+ logging.IncludeScopes = true; // necessário para correlação — ver Enrichment
51
+ logging.AddOtlpExporter();
52
+ });
53
+ ```
54
+
55
+ > **Source name:** sempre `AgentOpenTelemetryConsts.DefaultSourceName` de `Microsoft.Agents.AI`.
56
+ > **NÃO usar** o source string `"Experimental.[pacote-antigo].*"` — pertence à família `Microsoft.Extensions.AI` 9.x, incompatível com MAF 1.0 GA.
57
+ > **Produção:** desabilite dados sensíveis — `EnableSensitiveTelemetryData = false` no agent — para não vazar prompt/response completos no backend de export.
58
+
59
+ ### Aspire Dashboard (dev/local)
60
+
61
+ Visualiza em tempo real: fluxo completo de conversas entre agents, ciclos de tool call (Model → Tool → Model), token usage e latência por chamada, error traces e retry patterns. Para ambientes hospedados (Coolify), exporte via OTLP para o backend de observability do projeto — ver `infrastructure-docker-coolify-deploy` para o setup de Serilog/JSON console log que alimenta o mesmo pipeline de agregação.
62
+
63
+ ---
64
+
65
+ ## Enrichment — o que preencher em spans e logs
66
+
67
+ Setup sem enrichment produz traces tecnicamente corretos mas operacionalmente inúteis — você vê "uma chamada ao LLM aconteceu", não "por que ela demorou 8s" ou "qual feature/task gerou essa chamada". Preencha sempre:
68
+
69
+ ### Correlação entre trace, feature e requisição
70
+
71
+ ```csharp
72
+ using var activity = Activity.Current;
73
+ activity?.SetTag("morph.feature", featureName);
74
+ activity?.SetTag("morph.task_id", taskId);
75
+ activity?.SetTag("morph.correlation_id", correlationId); // mesmo ID em toda a cadeia de uma requisição de usuário
76
+ ```
77
+
78
+ Sem um `correlation_id` propagado manualmente através de chamadas assíncronas/filas (Hangfire, background jobs), você não consegue religar "o usuário reclamou às 14:32" a um trace específico — o `TraceId` do OpenTelemetry sozinho não sobrevive a um boundary de fila.
79
+
80
+ ### Atributos de custo e uso do modelo
81
+
82
+ ```csharp
83
+ activity?.SetTag("gen_ai.request.model", modelAlias); // alias do Model Registry, nunca o nome hardcoded
84
+ activity?.SetTag("gen_ai.usage.prompt_tokens", usage.PromptTokens);
85
+ activity?.SetTag("gen_ai.usage.completion_tokens", usage.CompletionTokens);
86
+ activity?.SetTag("gen_ai.response.finish_reason", finishReason);
87
+ ```
88
+
89
+ Nomeação `gen_ai.*` segue a convenção semântica OpenTelemetry para GenAI — mantém compatibilidade se o backend de observability tiver dashboards prontos para essa convenção.
90
+
91
+ ### Logging estruturado com `ILogger` — sempre com scope
92
+
93
+ ```csharp
94
+ using (_logger.BeginScope(new Dictionary<string, object>
95
+ {
96
+ ["FeatureId"] = featureName,
97
+ ["TaskId"] = taskId,
98
+ ["AgentId"] = agentPersonaId
99
+ }))
100
+ {
101
+ _logger.LogInformation("Tool call {ToolName} started with args {Args}", toolName, args);
102
+ // ... chamada ...
103
+ _logger.LogInformation("Tool call {ToolName} completed in {ElapsedMs}ms", toolName, elapsed);
104
+ }
105
+ ```
106
+
107
+ - **Sempre** parâmetros nomeados no template (`{ToolName}`, não string interpolada) — permite querying estruturado no backend em vez de grep de texto livre.
108
+ - **Nunca** logar o conteúdo completo do prompt/response em `Information` — isso é PII/dado sensível do cliente por padrão. Logar em `Debug` apenas, e só se `EnableSensitiveTelemetryData` estiver habilitado explicitamente para o ambiente.
109
+ - **Nível de log por tipo de evento:** `Information` para início/fim de tool call e decisões do agent; `Warning` para retry/fallback de provider; `Error` apenas para falhas que geram resposta degradada ao usuário (não para toda exceção capturada e tratada).
110
+
111
+ ---
112
+
113
+ ## Investigação e análise — quando algo dá errado
114
+
115
+ Workflow para diagnosticar um incidente relatado ("o agente X respondeu errado/lento/nada às HH:MM"):
116
+
117
+ 1. **Ancore no correlation_id ou janela de tempo.** Se o relato tem um identificador (número de WhatsApp, feature, conversationId), busque por ele nos atributos (`morph.correlation_id`, `gen_ai.*`) — não pelo texto do log. Sem identificador, restrinja pela janela de tempo + `morph.feature`/`AgentId` antes de olhar qualquer trace individual.
118
+ 2. **Suba do trace raiz para os spans filhos.** O span raiz mostra a duração total; os filhos (`Function Calling`, `IChatClient`) mostram onde o tempo/erro realmente está. Não assuma — meça. Um "agente lento" é quase sempre UM tool call específico (chamada de API externa, query sem índice), não o LLM.
119
+ 3. **Correlacione com métricas antes de teorizar.** Confira a tabela "What to Monitor" abaixo pelo período do incidente — um pico de `tool call failure rate` ou `token usage` aponta a causa mais rápido que ler traces individuais um a um.
120
+ 4. **Reproduza com Debug ligado, nunca em produção.** Se a causa não estiver clara nos atributos estruturados, habilite `Debug` (com dados sensíveis, se necessário) num ambiente de staging com o mesmo input — nunca habilite log de prompt/response completo em produção para investigar.
121
+ 5. **Documente a causa raiz em `decisions.md`** se a investigação levar a uma mudança de arquitetura (novo middleware de retry, novo timeout, novo cache) — não só no commit message.
122
+
123
+ ### What to Monitor
124
+
125
+ | Metric | Purpose | Alert Threshold |
126
+ |--------|---------|------------------|
127
+ | Token usage per request | Cost control | > 10K tokens/request |
128
+ | Latency per agent call | Performance | > 5s for simple tasks |
129
+ | Tool call failure rate | Reliability | > 5% failures |
130
+ | Cache hit rate | Cost optimization | < 50% (tune strategy) |
131
+ | Model drift | Quality | Evaluation score drop > 10% |
132
+
133
+ ---
134
+
135
+ ## Checklist (verifiable by morph-eval)
136
+
137
+ - [ ] OpenTelemetry configurado com `AgentOpenTelemetryConsts.DefaultSourceName` (traces + metrics + logging)
138
+ - [ ] `EnableSensitiveTelemetryData = false` fora de dev/staging
139
+ - [ ] Todo tool call relevante tem `correlation_id` propagado manualmente através de boundaries assíncronos (filas, background jobs)
140
+ - [ ] Logging via `ILogger` com `BeginScope` estruturado, nunca string interpolada em templates de log
141
+ - [ ] Nenhum log em `Information`/produção contém prompt/response completo
142
+ - [ ] Alertas configurados para os thresholds da tabela "What to Monitor" relevantes ao projeto
143
+
144
+ ---
145
+
146
+ ## References
147
+
148
+ - `ai-agents-production` — panorama de produção; esta seção era resumida lá, tratamento canônico agora aqui
149
+ - `ai-agents-middleware-patterns` — middleware de telemetria no nível `IChatClient` (`TelemetryMiddleware`)
150
+ - `infrastructure-docker-coolify-deploy` — Serilog/JSON console log para o pipeline de agregação em produção
151
+ - [OpenTelemetry Semantic Conventions for GenAI](https://opentelemetry.io/docs/specs/semconv/gen-ai/)
152
+ - [Agent Observability](https://learn.microsoft.com/agent-framework/user-guide/observability/)
153
+
154
+ ---
155
+
156
+ *MORPH-SPEC by Polymorphism Tech — ai-agents/observability-patterns.md v1.0 (2026-07-22)*
@@ -179,54 +179,9 @@ public async Task<WeatherResponse> GetWeatherAsync(
179
179
 
180
180
  ## Observability / OpenTelemetry
181
181
 
182
- ```csharp
183
- using OpenTelemetry;
184
- using OpenTelemetry.Trace;
185
- using OpenTelemetry.Metrics;
186
- using Microsoft.Agents.AI;
187
-
188
- // Enable on individual agents
189
- agent.WithOpenTelemetry();
190
-
191
- // Program.cs — full setup
192
- builder.Services.AddOpenTelemetry()
193
- .WithTracing(tracing =>
194
- {
195
- tracing.AddSource(AgentOpenTelemetryConsts.DefaultSourceName); // MAF 1.0 GA source
196
- tracing.AddSource(builder.Environment.ApplicationName);
197
- tracing.AddAspNetCoreInstrumentation();
198
- tracing.AddHttpClientInstrumentation();
199
- tracing.AddOtlpExporter();
200
- })
201
- .WithMetrics(metrics =>
202
- {
203
- metrics.AddMeter(AgentOpenTelemetryConsts.DefaultSourceName); // MAF 1.0 GA meter
204
- metrics.AddAspNetCoreInstrumentation();
205
- metrics.AddHttpClientInstrumentation();
206
- metrics.AddRuntimeInstrumentation();
207
- });
208
- ```
209
-
210
- > **Source name:** sempre `AgentOpenTelemetryConsts.DefaultSourceName` de `Microsoft.Agents.AI`.
211
- > **NÃO usar** o source string `"Experimental.[pacote-antigo].*"` — pertence à família `Microsoft.Extensions.AI 9.x`, incompatível com MAF 1.0 GA.
212
-
213
- ### Aspire Dashboard
214
-
215
- Visualiza traces de agents incluindo:
216
- - Fluxo completo de conversas entre agents
217
- - Tool call cycles (Model → Tool → Model)
218
- - Token usage e latência por chamada
219
- - Error traces e retry patterns
220
-
221
- ### What to Monitor
182
+ Setup, enrichment (span attributes, correlation IDs, structured logging) e o workflow de investigação/análise de logs em produção têm **tratamento canônico** em **`ai-agents-observability-patterns`**. Não duplicado aqui.
222
183
 
223
- | Metric | Purpose | Alert Threshold |
224
- |--------|---------|----------------|
225
- | Token usage per request | Cost control | > 10K tokens/request |
226
- | Latency per agent call | Performance | > 5s for simple tasks |
227
- | Tool call failure rate | Reliability | > 5% failures |
228
- | Cache hit rate | Cost optimization | < 50% (tune strategy) |
229
- | Model drift | Quality | Evaluation score drop > 10% |
184
+ > Em produção: source name sempre `AgentOpenTelemetryConsts.DefaultSourceName`; `EnableSensitiveTelemetryData = false` fora de dev/staging. Ver `ai-agents-observability-patterns` para o setup completo, o que preencher em cada span/log, e o workflow de investigação quando um incidente for reportado.
230
185
 
231
186
  ---
232
187
 
@@ -262,6 +217,7 @@ Visualiza traces de agents incluindo:
262
217
  - `ai-agents-sweet-spot` — decisão de arquitetura antes de middleware
263
218
  - `ai-agents-providers-model-registry` — Model Registry para `_modelRegistry.GetChatClient(...)`
264
219
  - `ai-agents-middleware-patterns` — **tratamento canônico** de middleware (código dos 3 níveis, telemetria, resilência, anti-hallucination)
220
+ - `ai-agents-observability-patterns` — **tratamento canônico** de observability (setup OpenTelemetry, enrichment de spans/logs, workflow de investigação)
265
221
  - `ai-agents-mcp-tools` — agente MAF consumindo MCP servers externos
266
222
  - `ai-agents-mcp-server` — projeto expondo capacidades como MCP server
267
223
  - `ai-agents-rag-custom-pgvector` — implementação completa de busca semântica (referida em Caching)
@@ -109,55 +109,6 @@
109
109
  "technology": "handlebars",
110
110
  "validatePlaceholders": true
111
111
  },
112
- {
113
- "id": "context",
114
- "kind": "template",
115
- "name": "Project Context",
116
- "path": "context/CONTEXT.md",
117
- "location": "framework",
118
- "category": "context",
119
- "phase": "proposal",
120
- "required": false,
121
- "description": "Project-level context with tech stack, active features, agents, standards",
122
- "outputName": "CONTEXT.md",
123
- "placeholders": [
124
- "AGENT_COUNT",
125
- "AGENT_TEAMS_DISPLAY_MODE",
126
- "AGENT_TEAMS_THRESHOLDS",
127
- "APP_INSIGHTS",
128
- "AZURE_LOCATION",
129
- "CONTAINER_ENV",
130
- "COOLIFY_APP_URL",
131
- "COOLIFY_SERVER",
132
- "DEVOPS_AREA_PATH",
133
- "DEVOPS_BUILD_PIPELINE",
134
- "DEVOPS_ORG",
135
- "DEVOPS_PROJECT",
136
- "DEVOPS_RELEASE_PIPELINE",
137
- "DEVOPS_WIKI_NAME",
138
- "DOTNET_VERSION",
139
- "EF_VERSION",
140
- "INFERRED_STANDARDS",
141
- "MORPH_VERSION",
142
- "NEON_PROJECT_ID",
143
- "NEON_REGION",
144
- "NEXTJS_VERSION",
145
- "OPENAI_MODEL",
146
- "PROJECT_DESCRIPTION",
147
- "PROJECT_NAME",
148
- "PROJECT_TYPE",
149
- "REPOSITORY_URL",
150
- "SQL_DATABASE",
151
- "SQL_SERVER",
152
- "TIMESTAMP",
153
- "UI_LIBRARY"
154
- ],
155
- "stackSpecific": false,
156
- "engine": "handlebars",
157
- "deprecated": false,
158
- "technology": "handlebars",
159
- "validatePlaceholders": true
160
- },
161
112
  {
162
113
  "id": "architecture",
163
114
  "kind": "template",
@@ -176,50 +127,6 @@
176
127
  "technology": "handlebars",
177
128
  "validatePlaceholders": true
178
129
  },
179
- {
180
- "id": "context-feature",
181
- "kind": "template",
182
- "name": "Feature Context",
183
- "path": "context/CONTEXT-FEATURE.md",
184
- "location": "framework",
185
- "category": "context",
186
- "phase": "proposal",
187
- "required": false,
188
- "description": "Feature-level context with progress, agents, tasks, decisions, validations",
189
- "outputName": "CONTEXT-FEATURE.md",
190
- "placeholders": [
191
- "ACTIVE_AGENTS_COUNT",
192
- "AGENT_TEAMS_DECISION",
193
- "COMPLEXITY",
194
- "CONTRACTS_PATH",
195
- "CURRENT_TASK",
196
- "DECISIONS_PATH",
197
- "DESCRIPTION",
198
- "FEATURE_ID",
199
- "FEATURE_NAME",
200
- "MORPH_VERSION",
201
- "PHASE",
202
- "PHASE_DESCRIPTION",
203
- "PROPOSAL_PATH",
204
- "RECAP_PATH",
205
- "SPEC_PATH",
206
- "STATUS",
207
- "TASKS_BLOCKED",
208
- "TASKS_COMPLETED",
209
- "TASKS_IN_PROGRESS",
210
- "TASKS_PATH",
211
- "TASKS_PROGRESS",
212
- "TASKS_TOTAL",
213
- "TEAM_LEAD",
214
- "TIMESTAMP",
215
- "VALIDATION_TIMESTAMP"
216
- ],
217
- "stackSpecific": false,
218
- "engine": "handlebars",
219
- "deprecated": false,
220
- "technology": "handlebars",
221
- "validatePlaceholders": true
222
- },
223
130
  {
224
131
  "id": "spec-examples",
225
132
  "kind": "template",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polymorphism-tech/morph-spec",
3
- "version": "8.2.1",
3
+ "version": "8.4.0",
4
4
  "description": "MORPH-SPEC: NLH (Natural Language Harness) for spec-driven development with Claude Code",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -0,0 +1,75 @@
1
+ /**
2
+ * `morph-spec telemetry [--json] [--feature <name>] [--limit <n>]`
3
+ *
4
+ * The reader surface over the harness event stream (.morph/logs/events.jsonl,
5
+ * written by the telemetry-log hook). Reconstructs the whole execution path of
6
+ * an NLH session: top skills, personas dispatched, standards (knowledge base)
7
+ * read, the tool mix, and the recent prompts (user + sub-agent).
8
+ *
9
+ * Read-only, always exits 0 (fail-open — an empty stream is an answer).
10
+ */
11
+
12
+ import chalk from 'chalk';
13
+ import { loadTelemetry, aggregateTelemetry } from '../../lib/telemetry/telemetry-reader.js';
14
+
15
+ // The knowledge-base count reflects EXPLICIT reads only. The core standards
16
+ // load via @-refs in rules (Layer 0/1 auto-load) — those are injected by
17
+ // Claude Code's rules system, not via the Read tool, so no hook ever sees them.
18
+ // A low count here means "few on-demand reads", NOT "standards barely used".
19
+ const STANDARDS_CAVEAT =
20
+ 'Só reads explícitos (via Read) são observáveis; standards auto-carregados por @-ref nas rules (Layer 0/1) não passam por tool call e ficam invisíveis aqui.';
21
+
22
+ function section(title, rows, fmt) {
23
+ if (!rows.length) return;
24
+ console.log('\n' + chalk.white.bold(title));
25
+ for (const r of rows) console.log(' ' + fmt(r));
26
+ }
27
+
28
+ /**
29
+ * @param {{ json?: boolean, feature?: string, limit?: number, cwd?: string }} [options]
30
+ */
31
+ export function telemetryCommand(options = {}) {
32
+ const events = loadTelemetry(options.cwd || process.cwd());
33
+ const summary = aggregateTelemetry(events, { feature: options.feature });
34
+
35
+ if (options.json) {
36
+ console.log(JSON.stringify({ ...summary, notes: { standards: STANDARDS_CAVEAT } }));
37
+ process.exit(0);
38
+ }
39
+
40
+ if (summary.total === 0) {
41
+ const scope = options.feature ? ` para a feature "${options.feature}"` : '';
42
+ console.log(chalk.gray(`Telemetria vazia${scope} — nenhum evento capturado ainda em .morph/logs/events.jsonl.`));
43
+ process.exit(0);
44
+ }
45
+
46
+ const scope = options.feature ? chalk.cyan(` · feature ${options.feature}`) : '';
47
+ console.log(chalk.white.bold(`Telemetria do harness — ${summary.total} eventos${scope}`));
48
+ if (summary.features.length) {
49
+ console.log(chalk.gray(`Features: ${summary.features.join(', ')}`));
50
+ }
51
+
52
+ section('Skills', summary.skills, s => `${chalk.green(s.name.padEnd(24))} ${s.count}`);
53
+ section('Personas despachadas', summary.personas, p => `${chalk.magenta(p.name.padEnd(24))} ${p.count}`);
54
+ section('Base de conhecimento (standards lidos explicitamente)', summary.standards,
55
+ s => `${chalk.yellow(String(s.count).padStart(3))}× ${s.path}`);
56
+ if (summary.standards.length || summary.tools.some(t => t.name === 'Read')) {
57
+ console.log(chalk.gray(` ⚠ ${STANDARDS_CAVEAT}`));
58
+ }
59
+ section('Mix de tools', summary.tools, t => `${t.name.padEnd(16)} ${t.count}`);
60
+
61
+ const limit = Number.isInteger(options.limit) && options.limit > 0 ? options.limit : 10;
62
+ const prompts = summary.prompts.slice(-limit);
63
+ if (prompts.length) {
64
+ console.log('\n' + chalk.white.bold(`Prompts (últimos ${prompts.length})`));
65
+ for (const p of prompts) {
66
+ const tag = p.source === 'user' ? chalk.blue('user ') : chalk.magenta('agent');
67
+ const where = p.feature ? chalk.gray(` [${p.feature}/${p.phase || '-'}]`) : '';
68
+ const oneLine = String(p.text || '').replace(/\s+/g, ' ').trim();
69
+ const preview = oneLine.length > 120 ? oneLine.slice(0, 117) + '...' : oneLine;
70
+ console.log(` ${tag}${where} ${preview}`);
71
+ }
72
+ }
73
+
74
+ process.exit(0);
75
+ }
@@ -14,6 +14,7 @@ import {
14
14
  import { resetMorphSettings } from '../../utils/claude-settings-manager.js';
15
15
  import { checkMissingAgents, checkAgentsDrift } from '../../utils/agents-installer.js';
16
16
  import { getProjectTags } from '../../lib/stack-filter.js';
17
+ import { auditFeatureLifecycle } from '../../core/state/lifecycle-audit.js';
17
18
 
18
19
  const isWindows = platform() === 'win32';
19
20
  /**
@@ -896,6 +897,22 @@ export async function doctorCommand(options = {}) {
896
897
  hasWarnings = true;
897
898
  }
898
899
 
900
+ // Feature-lifecycle consistency — the consolidated inconsistency report:
901
+ // gate-order violations (N approved with N-1 pending), identity-less
902
+ // features (no description), orphan folders and stale index entries. Warn
903
+ // only (advisory); the per-feature detail is printed after the summary.
904
+ const lifecycleIssues = auditFeatureLifecycle(targetPath);
905
+ if (lifecycleIssues.length === 0) {
906
+ checks.push({ name: 'feature lifecycle', status: 'ok' });
907
+ } else {
908
+ checks.push({
909
+ name: 'feature lifecycle',
910
+ status: 'warn',
911
+ msg: `${lifecycleIssues.length} inconsistenc${lifecycleIssues.length === 1 ? 'y' : 'ies'} (see below)`,
912
+ });
913
+ hasWarnings = true;
914
+ }
915
+
899
916
  // Check key templates exist (in framework package, not project copy)
900
917
  const frameworkTemplatesRoot = join(import.meta.dirname, '..', '..', '..', 'framework', 'templates');
901
918
  const keyTemplates = [
@@ -944,6 +961,17 @@ export async function doctorCommand(options = {}) {
944
961
  }
945
962
  }
946
963
 
964
+ // Per-feature detail for the lifecycle inconsistencies (item: doctor lists
965
+ // what's already wrong in the repo, e.g. plan approved with proposal pending).
966
+ if (lifecycleIssues.length) {
967
+ logger.blank();
968
+ console.log(chalk.yellow(' Feature lifecycle inconsistencies:'));
969
+ for (const issue of lifecycleIssues) {
970
+ console.log(chalk.gray(` • ${issue.feature} [${issue.type}] — ${issue.detail}`));
971
+ }
972
+ console.log(chalk.gray(" Fix: 'morph-spec approve' (order), '--description' on create, or 'morph-spec delete' for dead scaffolds."));
973
+ }
974
+
947
975
  logger.blank();
948
976
 
949
977
  if (hasErrors) {
@@ -2,6 +2,7 @@ import chalk from 'chalk';
2
2
  import { existsSync, mkdirSync } from 'fs';
3
3
  import { join } from 'path';
4
4
  import { getFeature, setApprovalGate, derivePhase } from '../../core/state/state-manager.js';
5
+ import { unmetPrereqs } from '../../core/state/gate-order.js';
5
6
 
6
7
  /**
7
8
  * `morph-spec advance <feature>` — approve the current phase's gate AND scaffold
@@ -57,6 +58,22 @@ export async function advanceCommand(featureName, options = {}) {
57
58
  const gate = PHASE_GATE[phase];
58
59
  const approvedBy = resolveApprovedBy(options);
59
60
 
61
+ // Gate monotonicity (mirrors approve.js): advance is a gate write-path too,
62
+ // so it must not stamp gate N while a predecessor is pending. In the
63
+ // sanctioned flow advance is always in-order (it approves G1 before the plan
64
+ // artifact that flips the phase to plan exists), but an anomalous filesystem
65
+ // state — e.g. 2-plan/spec.md present without Gate 1, the lead-termometro
66
+ // shape — would otherwise let advance deepen the violation by stamping G2.
67
+ // Escape via --force for deliberate recovery.
68
+ if (gate) {
69
+ const unmet = unmetPrereqs(gate, feature.approvalGates);
70
+ if (unmet.length && !options.force) {
71
+ console.error(chalk.red(`\n❌ Cannot advance past the ${phase} phase — prerequisite gate(s) not approved: ${unmet.join(', ')}.`));
72
+ console.error(chalk.gray(` Gates must be approved in order (${unmet.join(' → ')} → ${gate}). Approve them first, or pass --force.\n`));
73
+ process.exit(1);
74
+ }
75
+ }
76
+
60
77
  // Hotfix backstop (defensive, mirrors approve.js): the phase==='review'
61
78
  // early-return above already stops advance from ever reaching a
62
79
  // gate==='review' approval, but guard the approval itself too so this
@@ -3,6 +3,7 @@ import chalk from 'chalk';
3
3
  import { existsSync } from 'fs';
4
4
  import { join } from 'path';
5
5
  import { getFeature, setApprovalGate, getApprovalGate, getApprovalHistory, derivePhase } from '../../core/state/state-manager.js';
6
+ import { unmetPrereqs } from '../../core/state/gate-order.js';
6
7
 
7
8
  /**
8
9
  * Unapprove action function - Revoke a previously approved gate
@@ -99,6 +100,18 @@ export async function approveCommand(featureName, gateName, options = {}) {
99
100
  return;
100
101
  }
101
102
 
103
+ // Gate monotonicity: a gate may only be approved once its predecessors are
104
+ // approved (proposal → plan → review; uiux requires proposal). Prevents the
105
+ // lead-termometro shape — plan.approved with proposal pending. Policy-stamped
106
+ // gates count as approved, so chore/hotfix satisfy prereqs naturally.
107
+ // Escape via --force for deliberate recovery.
108
+ const unmet = unmetPrereqs(gateName, feature.approvalGates);
109
+ if (unmet.length && !options.force) {
110
+ console.error(chalk.red(`\n❌ Cannot approve "${gateName}" — prerequisite gate(s) not approved: ${unmet.join(', ')}.`));
111
+ console.log(chalk.gray(` Gates must be approved in order (${unmet.map((u) => u).join(' → ')} → ${gateName}). Approve them first, or pass --force.\n`));
112
+ process.exit(1);
113
+ }
114
+
102
115
  // Resolve who approved BEFORE the hotfix backstop — the backstop gates on
103
116
  // the resolved signature, not the raw --mode string (see below).
104
117
  //
@@ -1,5 +1,5 @@
1
1
  import chalk from 'chalk';
2
- import { mkdirSync, cpSync, readFileSync, writeFileSync } from 'fs';
2
+ import { mkdirSync, cpSync, readFileSync, writeFileSync, existsSync } from 'fs';
3
3
  import { join } from 'path';
4
4
  import { createFeature, setApprovalGate, getFeature } from '../../core/state/state-manager.js';
5
5
  import { WORK_TYPES, DEFAULT_WORK_TYPE, POLICY_APPROVER_PREFIX, isValidWorkType, getWorkType } from '../../core/work-types.js';
@@ -98,10 +98,30 @@ export async function createCommand(featureName, options = {}) {
98
98
  const now = new Date().toISOString();
99
99
  const { workType, workTypeDetection } = resolveWorkType(options, now);
100
100
 
101
+ // Identity at birth: every feature is stamped name (slug by default) +
102
+ // description, so it is never an anonymous {status,updatedAt} shell.
103
+ // `--request` (which the router already consumes) doubles as the
104
+ // description seed. A NEW feature with no description source is refused —
105
+ // the description is the one identity field a human must supply. An
106
+ // idempotent re-run on an EXISTING feature never demands it.
107
+ const description = options.description ?? options.request ?? null;
108
+ // Existence check via the filesystem, NOT getFeature/loadState — loadState
109
+ // throws when no state exists yet (a feature can be the first morph action
110
+ // in a fresh project), which would break birth-from-nothing.
111
+ const alreadyExists = existsSync(join(process.cwd(), '.morph', 'features', featureName, 'feature.json'));
112
+ if (!alreadyExists && (description === null || String(description).trim() === '')) {
113
+ console.error(chalk.red(`\n❌ A feature needs a description at birth: "${featureName}"`));
114
+ console.error(chalk.gray(' Pass --description "<what/why>" (or --request "<pedido>", which seeds it).'));
115
+ console.error(chalk.gray(' This keeps features identifiable — no more anonymous scaffolds.\n'));
116
+ process.exit(1);
117
+ }
118
+
101
119
  const { feature, created } = await createFeature(featureName, {
102
120
  status: options.status,
103
121
  workType,
104
122
  workTypeDetection,
123
+ name: options.name,
124
+ description: description ?? undefined,
105
125
  });
106
126
 
107
127
  const featureDir = join(process.cwd(), '.morph', 'features', featureName);