sinapse-ai 7.4.7 → 7.5.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 (29) hide show
  1. package/.claude/CLAUDE.md +10 -7
  2. package/.claude/rules/documentation-first.md +77 -0
  3. package/.claude/rules/mandatory-delegation.md +96 -0
  4. package/.codex/instructions.md +2 -1
  5. package/.sinapse-ai/constitution.md +59 -6
  6. package/.sinapse-ai/core/doctor/checks/constitution-consistency.js +116 -0
  7. package/.sinapse-ai/core/doctor/checks/index.js +10 -2
  8. package/.sinapse-ai/core/doctor/index.js +4 -3
  9. package/.sinapse-ai/core/health-check/checks/project/constitution-consistency.js +157 -0
  10. package/.sinapse-ai/core/health-check/checks/project/index.js +2 -0
  11. package/.sinapse-ai/data/entity-registry.yaml +807 -777
  12. package/.sinapse-ai/data/registry-update-log.jsonl +16 -0
  13. package/.sinapse-ai/development/tasks/dev-develop-story.md +14 -6
  14. package/.sinapse-ai/development/tasks/health-check.yaml +2 -2
  15. package/.sinapse-ai/development/templates/chrome-brain/knowledge-base/claude-in-chrome.md +62 -0
  16. package/.sinapse-ai/install-manifest.yaml +29 -17
  17. package/.sinapse-ai/product/templates/ide-rules/claude-rules.md +10 -6
  18. package/README.en.md +10 -8
  19. package/README.md +10 -8
  20. package/bin/modules/chrome-brain-installer.js +164 -29
  21. package/bin/sinapse.js +8 -0
  22. package/docs/framework/memory-lifecycle.md +1 -1
  23. package/docs/getting-started.md +2 -2
  24. package/docs/guides/user-guide.md +9 -7
  25. package/docs/guides/workflows/xref-phase6-supporting.md +1 -1
  26. package/docs/guides/workflows-guide.md +1 -1
  27. package/package.json +1 -1
  28. package/packages/sinapse-install/src/capabilities/chrome-brain.js +183 -12
  29. package/squads/claude-code-mastery/agents/project-integrator.md +1 -1
package/.claude/CLAUDE.md CHANGED
@@ -17,11 +17,12 @@ O SINAPSE possui uma **Constitution formal** com princípios inegociáveis e gat
17
17
  |--------|-----------|------------|
18
18
  | I | CLI First | NON-NEGOTIABLE |
19
19
  | II | Agent Authority | NON-NEGOTIABLE |
20
- | III | Story-Driven Development | MUST |
20
+ | III | Documentation-First Development | NON-NEGOTIABLE |
21
21
  | IV | No Invention | MUST |
22
22
  | V | Quality First | MUST |
23
23
  | VI | Absolute Imports | SHOULD |
24
24
  | VII | Ecosystem Metrics Accuracy | NON-NEGOTIABLE |
25
+ | VIII | Mandatory Delegation | NON-NEGOTIABLE |
25
26
 
26
27
  **Gates automáticos bloqueiam violações.** Consulte a Constitution para detalhes completos.
27
28
 
@@ -147,12 +148,14 @@ Use prefixo `*` para comandos:
147
148
  ---
148
149
 
149
150
  <!-- FRAMEWORK-OWNED: Generated by SINAPSE installer, do not customize -->
150
- ## Story-Driven Development
151
-
152
- 1. **Trabalhe a partir de stories** - Todo desenvolvimento começa com uma story em `docs/stories/`
153
- 2. **Atualize progresso** - Marque checkboxes conforme completa: `[ ]` `[x]`
154
- 3. **Rastreie mudanças** - Mantenha a seção File List na story
155
- 4. **Siga critérios** - Implemente exatamente o que os acceptance criteria especificam
151
+ ## Documentation-First Development (NON-NEGOTIABLE)
152
+
153
+ 1. **Pipeline automatico** - Todo briefing segue: Epic Story Validacao → Implementacao
154
+ 2. **Story validada obrigatoria** - Nenhum codigo sem story com status >= Ready
155
+ 3. **Trabalhe a partir de stories** - Todo desenvolvimento começa com uma story em `docs/stories/`
156
+ 4. **Atualize progresso** - Marque checkboxes conforme completa: `[ ]` `[x]`
157
+ 5. **Rastreie mudanças** - Mantenha a seção File List na story
158
+ 6. **Siga critérios** - Implemente exatamente o que os acceptance criteria especificam
156
159
 
157
160
  ### Workflow de Story
158
161
  ```
@@ -0,0 +1,77 @@
1
+ # Documentation-First Development (NON-NEGOTIABLE)
2
+
3
+ > **Constitution Article III — Elevated to NON-NEGOTIABLE**
4
+ > Applies to ALL agents, ALL projects, ALL requests. No exceptions.
5
+
6
+ ## Rule
7
+
8
+ Before ANY code implementation begins, the full documentation pipeline MUST be completed. This is AUTOMATIC behavior — no user needs to request it.
9
+
10
+ ### Required Pipeline
11
+
12
+ ```
13
+ User briefing → Epic (if new initiative) → Story → Validation → Implementation
14
+ ```
15
+
16
+ 1. **Epic** — The initiative MUST have an epic defined (or an existing one identified)
17
+ 2. **Story** — Each work unit MUST have a story file in `docs/stories/` with:
18
+ - Clear acceptance criteria (Given/When/Then preferred)
19
+ - Defined scope (IN/OUT)
20
+ - Dependencies mapped
21
+ - Complexity estimate
22
+ 3. **Validation** — Story MUST be validated (@product-lead) before implementation starts
23
+ 4. **Status** — Story status MUST be >= `Ready` before any code is written
24
+
25
+ ## Automatic Behavior (NON-NEGOTIABLE)
26
+
27
+ This is NOT something the user needs to request. It happens AUTOMATICALLY on every briefing:
28
+
29
+ | User Says | Agent Does |
30
+ |-----------|-----------|
31
+ | "Implementa feature X" | Creates story FIRST, then implements |
32
+ | "Corrige esse bug" | Creates bug-fix story FIRST, then fixes |
33
+ | "Faz isso rapidinho" | Creates story anyway — no shortcuts |
34
+ | "Pula a documentacao" | REFUSES. Explains this is NON-NEGOTIABLE |
35
+ | "So quero o codigo" | Routes to @sprint-lead for story, then @developer |
36
+
37
+ ## Gate: BLOCK
38
+
39
+ No implementation proceeds without ALL of these:
40
+ - Story file exists in `docs/stories/`
41
+ - Story has acceptance criteria defined
42
+ - Story has scope (IN/OUT) documented
43
+ - Story status is `Ready` or higher (validated by @product-lead)
44
+
45
+ **Attempting to write code without a valid story → BLOCKED.**
46
+
47
+ ## Workflow Enforcement
48
+
49
+ ### CORRECT Flow (always)
50
+ ```
51
+ User briefing
52
+ → @sprint-lead *draft (create story)
53
+ → @product-lead *validate (validate story)
54
+ → @developer *develop (implement)
55
+ → @quality-gate *qa-gate (quality check)
56
+ → @devops *push (deploy)
57
+ ```
58
+
59
+ ### FORBIDDEN Flow (never)
60
+ ```
61
+ User briefing → @developer *develop (BLOCKED — no story)
62
+ User briefing → Direct code writing (BLOCKED — no story)
63
+ ```
64
+
65
+ ## Exception
66
+
67
+ The ONLY exception is framework governance work by @sinapse-orqx (constitutional amendments, ecosystem health), which operates above the story layer. Even then, changes SHOULD be documented.
68
+
69
+ ## Anti-Patterns (FORBIDDEN)
70
+
71
+ - Writing ANY code without a story
72
+ - "Quick fix" without documentation
73
+ - Implementing features based only on verbal description
74
+ - Skipping story validation
75
+ - Starting implementation with a Draft story (must be Ready)
76
+ - Treating documentation as "optional" or "we'll do it later"
77
+ - Any agent accepting implementation work without verifying story exists
@@ -0,0 +1,96 @@
1
+ # Mandatory Delegation (NON-NEGOTIABLE)
2
+
3
+ > **Constitution Article VIII — NON-NEGOTIABLE**
4
+ > Applies to Imperator (sinapse-orqx) and ALL orchestrator agents (*-orqx).
5
+
6
+ ## Rule
7
+
8
+ Orchestrators NEVER execute domain work directly. They ALWAYS:
9
+
10
+ 1. **Absorb** — Understand the user's request fully
11
+ 2. **Diagnose** — Identify which domain(s) and specialist(s) are needed
12
+ 3. **Delegate** — Route to the appropriate specialist agent
13
+ 4. **Coordinate** — Track progress and handle handoffs between agents
14
+
15
+ This is AUTOMATIC and INVIOLABLE. The user never needs to ask for delegation — it happens on every single request.
16
+
17
+ ## Even When Explicitly Asked
18
+
19
+ If the user says ANY of these:
20
+ - "voce faz"
21
+ - "faz voce mesmo"
22
+ - "nao delega, faz direto"
23
+ - "I want YOU to write the code"
24
+ - "just do it yourself"
25
+ - "implementa isso ai"
26
+
27
+ The orchestrator MUST still delegate. The correct response pattern is:
28
+
29
+ > "Absorvi o briefing. Delegando para @{specialist-agent} que e o especialista nesse dominio."
30
+
31
+ **NEVER** execute the work directly. **ALWAYS** delegate to the specialist, no matter what the user says.
32
+
33
+ ## Delegation Matrix
34
+
35
+ ### Framework Agents (Development Workflow)
36
+
37
+ | Request Type | Delegate To |
38
+ |-------------|-------------|
39
+ | Code implementation | @developer (Dex) |
40
+ | Story creation | @sprint-lead (River) |
41
+ | Story validation | @product-lead (Pax) |
42
+ | Architecture decisions | @architect (Aria) |
43
+ | Quality/testing | @quality-gate (Quinn) |
44
+ | Database work | @data-engineer (Dara) |
45
+ | UX/UI design | @ux-design-expert (Uma) |
46
+ | Git push/PR/release | @devops (Gage) |
47
+ | Epic orchestration | @project-lead (Morgan) |
48
+ | Research/analysis | @analyst (Alex) |
49
+
50
+ ### Squad Orchestrators (Domain Expertise)
51
+
52
+ | Request Domain | Delegate To |
53
+ |---------------|-------------|
54
+ | Branding, identidade visual | @brand-orqx (Meridian) |
55
+ | Vendas, CRM, pipeline | @commercial-orqx (Pipeline) |
56
+ | Conteudo, editorial | @content-orqx |
57
+ | Copywriting, persuasao | @copy-orqx (Quill) |
58
+ | Animacoes web, motion | @animations-orqx (Kinetic) |
59
+ | UX/UI, design system | @design-orqx (Nexus) |
60
+ | Financeiro, pricing | @finance-orqx (Ledger) |
61
+ | Growth, SEO, analytics | @growth-orqx (Catalyst) |
62
+ | Midia paga, ads | @paidmedia-orqx (Apex) |
63
+ | Produto, roadmap | @product-orqx (Vector) |
64
+ | Pesquisa, inteligencia | @research-orqx (Prism) |
65
+ | Claude Code mastery | @claude-orqx (Nucleus) |
66
+ | Conselho estrategico | @council-orqx (Zenith) |
67
+ | Storytelling, pitch | @storytelling-orqx (Arc) |
68
+ | Cybersecurity | @cyber-orqx (Fortress) |
69
+ | Clonagem cognitiva | @cloning-orqx (Helix) |
70
+ | Cursos, workshops | @courses-orqx (Syllabus) |
71
+
72
+ ## What Orchestrators CAN Do (their actual domain)
73
+
74
+ Orchestrators have their OWN domain of expertise:
75
+
76
+ | Orchestrator | Own Domain (can execute directly) |
77
+ |-------------|----------------------------------|
78
+ | Imperator (sinapse-orqx) | Routing, diagnostico, plano de orquestracao, coordenacao cross-squad, framework governance |
79
+ | Squad *-orqx | Routing intra-squad, coordenacao de agentes do squad, handoff management |
80
+
81
+ Everything OUTSIDE their orchestration domain MUST be delegated.
82
+
83
+ ## Anti-Patterns (FORBIDDEN)
84
+
85
+ - Orchestrator writing application code
86
+ - Orchestrator making architectural decisions without @architect
87
+ - Orchestrator creating stories without @sprint-lead
88
+ - Orchestrator running quality checks without @quality-gate
89
+ - Orchestrator doing database work without @data-engineer
90
+ - Orchestrator doing ANY specialist work outside of orchestration
91
+ - Saying "vou fazer isso eu mesmo" instead of delegating
92
+ - Absorbing a request and executing it instead of routing
93
+
94
+ ## Enforcement
95
+
96
+ Any response from an orchestrator that contains direct domain work (code, schema, copy, etc.) without having first delegated to the appropriate specialist is a **constitutional violation** and must be corrected immediately.
@@ -70,8 +70,9 @@ Agent commands. Only work when an agent is active:
70
70
  Follow `.sinapse-ai/constitution.md`:
71
71
  - CLI First (NON-NEGOTIABLE)
72
72
  - Agent Authority: only @devops can push/PR
73
- - Story-Driven Development
73
+ - Documentation-First Development (NON-NEGOTIABLE)
74
74
  - Quality First: lint + typecheck + test before done
75
+ - Mandatory Delegation (NON-NEGOTIABLE)
75
76
 
76
77
  ## Quality Gates
77
78
 
@@ -1,6 +1,6 @@
1
1
  # SINAPSE Constitution
2
2
 
3
- > **Version:** 1.0.0 | **Ratified:** 2025-01-30 | **Last Amended:** 2025-01-30
3
+ > **Version:** 2.0.0 | **Ratified:** 2025-01-30 | **Last Amended:** 2026-03-30
4
4
 
5
5
  Este documento define os princípios fundamentais e inegociáveis do SINAPSE. Todos os agentes, tasks, e workflows DEVEM respeitar estes princípios. Violações são bloqueadas automaticamente via gates.
6
6
 
@@ -53,18 +53,32 @@ Cada agente tem autoridades exclusivas que não podem ser violadas.
53
53
 
54
54
  ---
55
55
 
56
- ### III. Story-Driven Development (MUST)
56
+ ### III. Documentation-First Development (NON-NEGOTIABLE)
57
57
 
58
- Todo desenvolvimento começa e termina com uma story.
58
+ Todo desenvolvimento começa e termina com documentação. Nenhum código é escrito sem que o pipeline completo de documentação seja executado primeiro. Este comportamento é AUTOMÁTICO — nenhum usuário precisa solicitar.
59
59
 
60
60
  **Regras:**
61
- - MUST: Nenhum código é escrito sem uma story associada
61
+ - MUST: Nenhum código é escrito sem uma story associada e validada
62
62
  - MUST: Stories DEVEM ter acceptance criteria claros antes de implementação
63
63
  - MUST: Progresso DEVE ser rastreado via checkboxes na story
64
64
  - MUST: File List DEVE ser mantida atualizada na story
65
- - SHOULD: Stories seguem o workflow: @product-lead/@sprint-lead cria @developer implementa → @quality-gate valida @devops push
65
+ - MUST: Story status DEVE ser >= Ready (validada por @product-lead) antes de qualquer código
66
+ - MUST: O pipeline Epic → Story → Validação → Implementação é AUTOMÁTICO em todo briefing
67
+ - MUST NOT: Nenhum agente pode aceitar trabalho de implementação sem verificar que a story existe e está validada
66
68
 
67
- **Gate:** `dev-develop-story.md` - BLOCK se não houver story válida
69
+ **Pipeline obrigatório (automático):**
70
+ ```
71
+ User briefing → @sprint-lead *draft → @product-lead *validate → @developer *develop → @quality-gate *qa-gate → @devops *push
72
+ ```
73
+
74
+ **Comportamento automático:**
75
+ - Quando usuário pede implementação → Cria story PRIMEIRO, depois implementa
76
+ - Quando usuário diz "pula a documentação" → RECUSA. Explica que é NON-NEGOTIABLE
77
+ - Quando bug é reportado → Cria story de bug-fix PRIMEIRO, depois corrige
78
+
79
+ **Gate:** `dev-develop-story.md` - BLOCK se não houver story válida com status >= Ready
80
+
81
+ **Rule file:** `.claude/rules/documentation-first.md`
68
82
 
69
83
  ---
70
84
 
@@ -154,6 +168,45 @@ Métricas do ecossistema (contagem de squads, agentes, tasks, orqx) DEVEM ser es
154
168
 
155
169
  ---
156
170
 
171
+ ### VIII. Mandatory Delegation (NON-NEGOTIABLE)
172
+
173
+ Orquestradores (sinapse-orqx e todos os *-orqx) NUNCA executam trabalho de domínio diretamente. Eles SEMPRE absorvem o pedido e delegam ao especialista correto. Este comportamento é AUTOMÁTICO e INVIOLÁVEL — mesmo que o usuário peça explicitamente para o orquestrador fazer o trabalho.
174
+
175
+ **Regras:**
176
+ - MUST: Orquestradores SEMPRE delegam trabalho de domínio ao agente especialista
177
+ - MUST: Delegação é automática — nenhum usuário precisa solicitar
178
+ - MUST: Mesmo quando o usuário diz "faça você mesmo" → delegar ao especialista
179
+ - MUST: Cada agente opera estritamente dentro de seu escopo de autoridade
180
+ - MUST NOT: Nenhum orquestrador pode executar implementação de código
181
+ - MUST NOT: Nenhum orquestrador pode fazer decisões arquiteturais sem @architect
182
+ - MUST NOT: Nenhum orquestrador pode criar stories sem @sprint-lead
183
+ - MUST NOT: Nenhum orquestrador pode executar quality gates sem @quality-gate
184
+
185
+ **O que orquestradores PODEM fazer (seu domínio):**
186
+ - Routing e diagnóstico de requests
187
+ - Produção de planos de orquestração
188
+ - Coordenação cross-squad e handoffs
189
+ - Framework governance (Imperator apenas)
190
+
191
+ **Delegação obrigatória:**
192
+
193
+ | Request Type | Delegate To |
194
+ |-------------|-------------|
195
+ | Código | @developer |
196
+ | Stories | @sprint-lead |
197
+ | Validação | @product-lead |
198
+ | Arquitetura | @architect |
199
+ | Qualidade | @quality-gate |
200
+ | Database | @data-engineer |
201
+ | Git push/PR | @devops |
202
+ | Domínio específico | @{domain}-orqx → specialist |
203
+
204
+ **Gate:** Qualquer resposta de orquestrador que contenha trabalho de domínio direto sem delegação é uma violação constitucional.
205
+
206
+ **Rule file:** `.claude/rules/mandatory-delegation.md`
207
+
208
+ ---
209
+
157
210
  ## Governance
158
211
 
159
212
  ### Amendment Process
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Doctor Check: Constitution Consistency
3
+ *
4
+ * Deep validation that Constitution articles are consistent across
5
+ * all framework documents. Checks source, generated domain, CLAUDE.md,
6
+ * AGENTS.md, and required rule files.
7
+ *
8
+ * @module sinapse-ai/doctor/checks/constitution-consistency
9
+ * @constitution Article VII - Ecosystem Metrics Accuracy
10
+ * @tag deep
11
+ */
12
+
13
+ const path = require('path');
14
+ const fs = require('fs');
15
+
16
+ const name = 'constitution-consistency';
17
+
18
+ /**
19
+ * Articles that MUST appear in consumer documents
20
+ * Key articles only — we check titles, not full content
21
+ */
22
+ const KEY_ARTICLES = [
23
+ 'CLI First',
24
+ 'Agent Authority',
25
+ 'Documentation-First Development',
26
+ 'No Invention',
27
+ 'Quality First',
28
+ 'Absolute Imports',
29
+ 'Ecosystem Metrics Accuracy',
30
+ 'Mandatory Delegation',
31
+ ];
32
+
33
+ /**
34
+ * Files that should reference Constitution articles
35
+ */
36
+ const CONSUMER_FILES = [
37
+ '.claude/CLAUDE.md',
38
+ 'AGENTS.md',
39
+ '.synapse/constitution',
40
+ ];
41
+
42
+ /**
43
+ * Rule files required for NON-NEGOTIABLE articles
44
+ */
45
+ const REQUIRED_RULES = [
46
+ '.claude/rules/documentation-first.md',
47
+ '.claude/rules/mandatory-delegation.md',
48
+ ];
49
+
50
+ async function run(context) {
51
+ const root = context.projectRoot;
52
+ const issues = [];
53
+
54
+ // Check 1: Constitution source exists
55
+ const srcPath = path.join(root, '.sinapse-ai', 'constitution.md');
56
+ if (!fs.existsSync(srcPath)) {
57
+ return {
58
+ check: name,
59
+ status: 'FAIL',
60
+ message: 'Constitution source not found at .sinapse-ai/constitution.md',
61
+ fixCommand: 'sinapse install',
62
+ };
63
+ }
64
+
65
+ const srcContent = fs.readFileSync(srcPath, 'utf8');
66
+
67
+ // Check 2: All key articles present in source
68
+ for (const article of KEY_ARTICLES) {
69
+ if (!srcContent.includes(article)) {
70
+ issues.push(`Source missing article: "${article}"`);
71
+ }
72
+ }
73
+
74
+ // Check 3: Consumer files reference articles
75
+ for (const relPath of CONSUMER_FILES) {
76
+ const filePath = path.join(root, relPath);
77
+ if (!fs.existsSync(filePath)) {
78
+ issues.push(`Consumer file missing: ${relPath}`);
79
+ continue;
80
+ }
81
+
82
+ const content = fs.readFileSync(filePath, 'utf8');
83
+ for (const article of KEY_ARTICLES) {
84
+ if (!content.includes(article)) {
85
+ issues.push(`${relPath} missing "${article}"`);
86
+ }
87
+ }
88
+ }
89
+
90
+ // Check 4: Required rule files exist
91
+ for (const rulePath of REQUIRED_RULES) {
92
+ const fullPath = path.join(root, rulePath);
93
+ if (!fs.existsSync(fullPath)) {
94
+ issues.push(`Required rule file missing: ${rulePath}`);
95
+ }
96
+ }
97
+
98
+ // Result
99
+ if (issues.length === 0) {
100
+ return {
101
+ check: name,
102
+ status: 'PASS',
103
+ message: `Constitution consistent (${KEY_ARTICLES.length} articles, ${CONSUMER_FILES.length} consumers, ${REQUIRED_RULES.length} rules)`,
104
+ fixCommand: null,
105
+ };
106
+ }
107
+
108
+ return {
109
+ check: name,
110
+ status: issues.length <= 2 ? 'WARN' : 'FAIL',
111
+ message: `${issues.length} consistency issue(s): ${issues.slice(0, 3).join('; ')}${issues.length > 3 ? ` (+${issues.length - 3} more)` : ''}`,
112
+ fixCommand: 'sinapse doctor --fix',
113
+ };
114
+ }
115
+
116
+ module.exports = { name, run };
@@ -22,9 +22,10 @@ const npmPackages = require('./npm-packages');
22
22
  const skillsCount = require('./skills-count');
23
23
  const commandsCount = require('./commands-count');
24
24
  const hooksClaudeCount = require('./hooks-claude-count');
25
+ const constitutionConsistency = require('./constitution-consistency');
25
26
 
26
- function loadChecks() {
27
- return [
27
+ function loadChecks(options = {}) {
28
+ const checks = [
28
29
  settingsJson,
29
30
  rulesFiles,
30
31
  agentMemory,
@@ -41,6 +42,13 @@ function loadChecks() {
41
42
  commandsCount,
42
43
  hooksClaudeCount,
43
44
  ];
45
+
46
+ // Deep checks — only run with --deep flag
47
+ if (options.deep) {
48
+ checks.push(constitutionConsistency);
49
+ }
50
+
51
+ return checks;
44
52
  }
45
53
 
46
54
  module.exports = { loadChecks };
@@ -34,17 +34,18 @@ async function runDoctorChecks(options = {}) {
34
34
  json = false,
35
35
  dryRun = false,
36
36
  quiet = false,
37
+ deep = false,
37
38
  projectRoot = process.cwd(),
38
39
  } = options;
39
40
 
40
41
  const context = {
41
42
  projectRoot,
42
43
  frameworkRoot: path.resolve(__dirname, '..', '..', '..'),
43
- options: { fix, json, dryRun, quiet },
44
+ options: { fix, json, dryRun, quiet, deep },
44
45
  };
45
46
 
46
- // Load and run all checks
47
- const checks = loadChecks();
47
+ // Load and run all checks (deep checks only with --deep flag)
48
+ const checks = loadChecks({ deep });
48
49
  const results = [];
49
50
 
50
51
  for (const checkModule of checks) {
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Constitution Consistency Check
3
+ *
4
+ * Deep validation that Constitution articles are consistent across
5
+ * all framework documents: constitution.md, generated domain file,
6
+ * CLAUDE.md, AGENTS.md, templates, and rule files.
7
+ *
8
+ * @module sinapse-ai/health-check/checks/project/constitution-consistency
9
+ * @version 1.0.0
10
+ * @constitution Article VII - Ecosystem Metrics Accuracy
11
+ */
12
+
13
+ const fs = require('fs');
14
+ const path = require('path');
15
+ const { BaseCheck, CheckSeverity, CheckDomain } = require('../../base-check');
16
+
17
+ /**
18
+ * Expected articles in Constitution v2.0.0
19
+ * Source of truth: .sinapse-ai/constitution.md
20
+ */
21
+ const EXPECTED_ARTICLES = [
22
+ { number: 'I', title: 'CLI First', severity: 'NON-NEGOTIABLE' },
23
+ { number: 'II', title: 'Agent Authority', severity: 'NON-NEGOTIABLE' },
24
+ { number: 'III', title: 'Documentation-First Development', severity: 'NON-NEGOTIABLE' },
25
+ { number: 'IV', title: 'No Invention', severity: 'MUST' },
26
+ { number: 'V', title: 'Quality First', severity: 'MUST' },
27
+ { number: 'VI', title: 'Absolute Imports', severity: 'SHOULD' },
28
+ { number: 'VII', title: 'Ecosystem Metrics Accuracy', severity: 'NON-NEGOTIABLE' },
29
+ { number: 'VIII', title: 'Mandatory Delegation', severity: 'NON-NEGOTIABLE' },
30
+ ];
31
+
32
+ /**
33
+ * Files that MUST reference the Constitution articles
34
+ */
35
+ const CONSTITUTION_CONSUMERS = [
36
+ { path: '.claude/CLAUDE.md', label: 'Project CLAUDE.md' },
37
+ { path: 'AGENTS.md', label: 'AGENTS.md' },
38
+ { path: '.synapse/constitution', label: 'Generated Constitution Domain' },
39
+ ];
40
+
41
+ /**
42
+ * Rule files required for NON-NEGOTIABLE articles
43
+ */
44
+ const REQUIRED_RULE_FILES = [
45
+ { article: 'III', file: '.claude/rules/documentation-first.md' },
46
+ { article: 'VIII', file: '.claude/rules/mandatory-delegation.md' },
47
+ ];
48
+
49
+ class ConstitutionConsistencyCheck extends BaseCheck {
50
+ constructor() {
51
+ super({
52
+ id: 'constitution-consistency',
53
+ name: 'Constitution Consistency',
54
+ description: 'Validates Constitution articles are consistent across all framework documents',
55
+ domain: CheckDomain.PROJECT,
56
+ severity: CheckSeverity.HIGH,
57
+ timeout: 10000,
58
+ cacheable: true,
59
+ tags: ['constitution', 'deep', 'consistency'],
60
+ });
61
+ }
62
+
63
+ async execute(context) {
64
+ const projectRoot = context.projectRoot || process.cwd();
65
+ const issues = [];
66
+ const details = { checked: [], issues: [] };
67
+
68
+ // Check 1: Constitution source exists
69
+ const constitutionPath = path.join(projectRoot, '.sinapse-ai', 'constitution.md');
70
+ if (!fs.existsSync(constitutionPath)) {
71
+ return this.fail('Constitution source file not found', {
72
+ recommendation: 'Run sinapse install to restore .sinapse-ai/constitution.md',
73
+ });
74
+ }
75
+ details.checked.push('constitution.md exists');
76
+
77
+ const constitutionContent = fs.readFileSync(constitutionPath, 'utf8');
78
+
79
+ // Check 2: All expected articles exist in source
80
+ for (const article of EXPECTED_ARTICLES) {
81
+ const pattern = new RegExp(`### ${article.number}\\..*${article.title}.*\\(${article.severity}\\)`, 'i');
82
+ if (!pattern.test(constitutionContent)) {
83
+ issues.push(`Article ${article.number} (${article.title}) not found or severity mismatch in constitution.md`);
84
+ }
85
+ }
86
+ details.checked.push('Article presence in source');
87
+
88
+ // Check 3: Consumer documents reference articles correctly
89
+ for (const consumer of CONSTITUTION_CONSUMERS) {
90
+ const filePath = path.join(projectRoot, consumer.path);
91
+ if (!fs.existsSync(filePath)) {
92
+ issues.push(`${consumer.label} not found at ${consumer.path}`);
93
+ continue;
94
+ }
95
+
96
+ const content = fs.readFileSync(filePath, 'utf8');
97
+
98
+ // Check that key article titles appear
99
+ for (const article of EXPECTED_ARTICLES) {
100
+ if (!content.includes(article.title)) {
101
+ issues.push(`${consumer.label} missing reference to "${article.title}"`);
102
+ }
103
+ }
104
+ }
105
+ details.checked.push('Consumer document references');
106
+
107
+ // Check 4: Required rule files exist for NON-NEGOTIABLE articles
108
+ for (const rule of REQUIRED_RULE_FILES) {
109
+ const rulePath = path.join(projectRoot, rule.file);
110
+ if (!fs.existsSync(rulePath)) {
111
+ issues.push(`Rule file missing for Article ${rule.article}: ${rule.file}`);
112
+ }
113
+ }
114
+ details.checked.push('Rule files for NON-NEGOTIABLE articles');
115
+
116
+ // Check 5: Generated constitution domain file is up-to-date
117
+ const generatedPath = path.join(projectRoot, '.synapse', 'constitution');
118
+ if (fs.existsSync(generatedPath)) {
119
+ const generatedContent = fs.readFileSync(generatedPath, 'utf8');
120
+
121
+ for (const article of EXPECTED_ARTICLES) {
122
+ const key = `CONSTITUTION_RULE_ART${EXPECTED_ARTICLES.indexOf(article) + 1}_0`;
123
+ if (!generatedContent.includes(article.title)) {
124
+ issues.push(`Generated constitution missing Article "${article.title}". Run generate-constitution.js`);
125
+ }
126
+ }
127
+ } else {
128
+ issues.push('Generated constitution domain file not found at .synapse/constitution');
129
+ }
130
+ details.checked.push('Generated domain file freshness');
131
+
132
+ // Result
133
+ details.issues = issues;
134
+ details.totalChecks = details.checked.length;
135
+ details.totalIssues = issues.length;
136
+
137
+ if (issues.length === 0) {
138
+ return this.pass(`Constitution consistent across ${details.totalChecks} validation points`, details);
139
+ }
140
+
141
+ if (issues.length <= 2) {
142
+ return this.warn(`${issues.length} minor consistency issue(s) found`, {
143
+ details,
144
+ recommendation: issues.join('; '),
145
+ });
146
+ }
147
+
148
+ return this.fail(`${issues.length} consistency issues found across Constitution references`, {
149
+ details,
150
+ recommendation: 'Run sinapse doctor --fix to regenerate constitution and sync documents',
151
+ healable: true,
152
+ healingTier: 2,
153
+ });
154
+ }
155
+ }
156
+
157
+ module.exports = ConstitutionConsistencyCheck;
@@ -17,6 +17,7 @@ const SinapseDirectoryCheck = require('./sinapse-directory');
17
17
  const AgentConfigCheck = require('./agent-config');
18
18
  const TaskDefinitionsCheck = require('./task-definitions');
19
19
  const WorkflowDependenciesCheck = require('./workflow-dependencies');
20
+ const ConstitutionConsistencyCheck = require('./constitution-consistency');
20
21
 
21
22
  /**
22
23
  * All project domain checks
@@ -30,4 +31,5 @@ module.exports = {
30
31
  AgentConfigCheck,
31
32
  TaskDefinitionsCheck,
32
33
  WorkflowDependenciesCheck,
34
+ ConstitutionConsistencyCheck,
33
35
  };