agent-enderun 0.6.1 → 0.6.6

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 (89) hide show
  1. package/.enderun/BRAIN_DASHBOARD.md +12 -12
  2. package/.enderun/PROJECT_MEMORY.md +17 -17
  3. package/.enderun/STATUS.md +11 -11
  4. package/.enderun/agents/README.md +40 -0
  5. package/.enderun/agents/analyst.md +238 -31
  6. package/.enderun/agents/backend.md +428 -18
  7. package/.enderun/agents/explorer.md +169 -31
  8. package/.enderun/agents/frontend.md +604 -76
  9. package/.enderun/agents/git.md +153 -62
  10. package/.enderun/agents/manager.md +433 -46
  11. package/.enderun/agents/mobile.md +143 -29
  12. package/.enderun/agents/native.md +191 -28
  13. package/.enderun/blueprints/README.md +82 -0
  14. package/.enderun/blueprints/backend/errors/config/meta.json +11 -0
  15. package/.enderun/blueprints/backend/errors/domain-error.ts +34 -55
  16. package/.enderun/docs/README.md +50 -0
  17. package/.enderun/docs/phase1-reference-app-execution-plan.md +177 -0
  18. package/.enderun/docs/structure-audit-2026-05-24.md +72 -0
  19. package/.enderun/knowledge/README.md +22 -0
  20. package/.enderun/knowledge/database_governance_guidelines.md +118 -0
  21. package/.enderun/knowledge/deployment_checklist.md +132 -6
  22. package/.enderun/knowledge/documentation_ownership.md +122 -0
  23. package/.enderun/knowledge/documentation_ownership_status.md +122 -0
  24. package/.enderun/knowledge/enterprise_capabilities_reference.md +149 -0
  25. package/.enderun/knowledge/enterprise_frontend_adaptation.md +232 -0
  26. package/.enderun/knowledge/enterprise_project_adaptation.md +168 -0
  27. package/.enderun/knowledge/framework_vs_user_project_boundary.md +52 -0
  28. package/.enderun/knowledge/frontend_professionalization_guidelines.md +111 -0
  29. package/.enderun/knowledge/frontend_real_battle_test_protocol.md +162 -0
  30. package/.enderun/knowledge/hermes_live_test_guidelines.md +90 -0
  31. package/.enderun/knowledge/manager_authority_audit_enforcement.md +104 -0
  32. package/.enderun/knowledge/project_scaffold_guidelines.md +99 -0
  33. package/.enderun/knowledge/reference_application_guidelines.md +90 -0
  34. package/ENDERUN.md +19 -5
  35. package/README.md +132 -657
  36. package/antigravity.md +15 -0
  37. package/bin/cli.js +92 -27
  38. package/bin/hermes-sandbox.js +136 -0
  39. package/docs/README.md +33 -3
  40. package/docs/action-plan-2026.md +119 -0
  41. package/docs/getting-started.md +271 -0
  42. package/docs/roadmap.md +142 -0
  43. package/framework-mcp/README.md +1 -1
  44. package/framework-mcp/dist/index.js +0 -0
  45. package/framework-mcp/dist/schemas.js +6 -0
  46. package/framework-mcp/dist/tools/academy.js +6 -8
  47. package/framework-mcp/dist/tools/codebase.js +6 -6
  48. package/framework-mcp/dist/tools/contract.js +94 -4
  49. package/framework-mcp/dist/tools/database.js +8 -3
  50. package/framework-mcp/dist/tools/framework.js +7 -11
  51. package/framework-mcp/dist/tools/git.js +2 -2
  52. package/framework-mcp/dist/tools/knowledge.js +5 -5
  53. package/framework-mcp/dist/tools/memory.js +5 -7
  54. package/framework-mcp/dist/tools/messages.js +76 -16
  55. package/framework-mcp/dist/tools/repository.js +4 -4
  56. package/framework-mcp/dist/tools/scaffold.js +6 -3
  57. package/framework-mcp/dist/tools/security.js +4 -4
  58. package/framework-mcp/dist/utils.js +2 -2
  59. package/framework-mcp/package.json +1 -1
  60. package/framework-mcp/src/schemas.ts +7 -0
  61. package/framework-mcp/src/tools/academy.ts +5 -9
  62. package/framework-mcp/src/tools/codebase.ts +6 -6
  63. package/framework-mcp/src/tools/contract.ts +114 -4
  64. package/framework-mcp/src/tools/database.ts +8 -3
  65. package/framework-mcp/src/tools/framework.ts +8 -11
  66. package/framework-mcp/src/tools/git.ts +2 -2
  67. package/framework-mcp/src/tools/knowledge.ts +6 -7
  68. package/framework-mcp/src/tools/memory.ts +5 -6
  69. package/framework-mcp/src/tools/messages.ts +94 -28
  70. package/framework-mcp/src/tools/repository.ts +5 -6
  71. package/framework-mcp/src/tools/scaffold.ts +9 -6
  72. package/framework-mcp/src/tools/security.ts +4 -4
  73. package/framework-mcp/src/utils.ts +19 -2
  74. package/framework-mcp/tsconfig.json +1 -1
  75. package/gemini.md +4 -4
  76. package/package.json +11 -7
  77. package/panda.config.ts +3 -1
  78. package/.enderun/benchmarks/.gitkeep +0 -0
  79. package/.enderun/blueprints/backend/middleware/error-handler.ts +0 -24
  80. package/.enderun/blueprints/backend/types/api.ts +0 -20
  81. package/.enderun/blueprints/backend/types/brands.ts +0 -12
  82. package/.enderun/blueprints/backend/types/constants.ts +0 -34
  83. package/.enderun/blueprints/backend/types/index.ts +0 -49
  84. package/.enderun/blueprints/backend/types/logs.ts +0 -16
  85. package/.enderun/blueprints/backend/types/models.ts +0 -65
  86. package/.enderun/blueprints/frontend/ui/Button.tsx +0 -60
  87. package/.enderun/blueprints/frontend/ui/Input.tsx +0 -43
  88. package/.enderun/monitoring/.gitkeep +0 -0
  89. package/gemini-extension.json +0 -13
@@ -1,84 +1,63 @@
1
- import { ApiError } from "../types/index.js";
2
-
3
1
  /**
4
- * Base Domain Error
5
- * All specialized errors should extend this class.
2
+ * GOLD STANDARD BLUEPRINT
3
+ * Category: backend/errors
4
+ * Name: DomainError Hierarchy
5
+ * Version: 1.0.0
6
+ * Description: Standardized, typed error system for all backend services.
7
+ *
8
+ * Usage:
9
+ * 1. Copy this file to apps/backend/src/errors/domain-error.ts
10
+ * 2. Create index.ts to re-export all error classes
11
+ * 3. Import and use in controllers/services (never throw raw Error)
6
12
  */
7
- export class DomainError extends Error {
8
- constructor(
9
- public readonly code: string,
10
- public readonly statusCode: number,
11
- message: string,
12
- public readonly details?: unknown
13
- ) {
14
- super(message);
15
- this.name = "DomainError";
16
- }
17
13
 
18
- /**
19
- * Converts the error to a standard API response format defined in shared-types
20
- */
21
- toApiResponse(): ApiError {
22
- return {
23
- error: {
24
- code: this.code,
25
- message: this.message,
26
- details: this.details,
27
- },
28
- };
14
+ export abstract class DomainError extends Error {
15
+ public readonly statusCode: number;
16
+ public readonly code: string;
17
+
18
+ constructor(message: string, statusCode: number, code: string) {
19
+ super(message);
20
+ this.name = this.constructor.name;
21
+ this.statusCode = statusCode;
22
+ this.code = code;
23
+ Error.captureStackTrace(this, this.constructor);
29
24
  }
30
25
  }
31
26
 
32
- /**
33
- * 404 - Not Found
34
- */
35
27
  export class NotFoundError extends DomainError {
36
- constructor(entity: string, details?: unknown) {
37
- super("NOT_FOUND", 404, `${entity} not found.`, details);
28
+ constructor(resource: string) {
29
+ super(`${resource} not found`, 404, 'NOT_FOUND');
38
30
  }
39
31
  }
40
32
 
41
- /**
42
- * 400 - Validation Error
43
- */
44
33
  export class ValidationError extends DomainError {
45
- constructor(message: string, details?: unknown) {
46
- super("VALIDATION_ERROR", 400, message, details);
34
+ constructor(message: string, details?: Record<string, unknown>) {
35
+ super(message, 400, 'VALIDATION_ERROR');
36
+ // @ts-ignore - attach details for logging
37
+ this.details = details;
47
38
  }
48
39
  }
49
40
 
50
- /**
51
- * 401 - Unauthorized
52
- */
53
41
  export class UnauthorizedError extends DomainError {
54
- constructor(message: string = "Authentication required.", details?: unknown) {
55
- super("UNAUTHORIZED", 401, message, details);
42
+ constructor(message = 'Unauthorized') {
43
+ super(message, 401, 'UNAUTHORIZED');
56
44
  }
57
45
  }
58
46
 
59
- /**
60
- * 403 - Forbidden
61
- */
62
47
  export class ForbiddenError extends DomainError {
63
- constructor(message: string = "Access denied.", details?: unknown) {
64
- super("FORBIDDEN", 403, message, details);
48
+ constructor(message = 'Forbidden') {
49
+ super(message, 403, 'FORBIDDEN');
65
50
  }
66
51
  }
67
52
 
68
- /**
69
- * 409 - Conflict
70
- */
71
53
  export class ConflictError extends DomainError {
72
- constructor(message: string, details?: unknown) {
73
- super("CONFLICT", 409, message, details);
54
+ constructor(message: string) {
55
+ super(message, 409, 'CONFLICT');
74
56
  }
75
57
  }
76
58
 
77
- /**
78
- * 500 - Internal Server Error
79
- */
80
59
  export class InternalServerError extends DomainError {
81
- constructor(message: string = "An unexpected error occurred.", details?: unknown) {
82
- super("INTERNAL_ERROR", 500, message, details);
60
+ constructor(message = 'Internal server error') {
61
+ super(message, 500, 'INTERNAL_ERROR');
83
62
  }
84
63
  }
@@ -0,0 +1,50 @@
1
+ # .enderun/docs/ — Framework Governance Documentation
2
+
3
+ **Owner:** @manager
4
+ **Created:** 24 May 2026
5
+ **Purpose:** Clear separation of governance, audit, and internal framework documentation belonging to the `.enderun/` layer.
6
+
7
+ ---
8
+
9
+ ## What This Folder Contains
10
+
11
+ This folder contains **only** Agent Enderun's own internal rules, policies, and governance documents.
12
+
13
+ ### Content Summary
14
+
15
+ - `api/` → MCP tool contracts, auth, errors (synchronized with `{{FRAMEWORK_DIR}}/docs/api/`)
16
+ - `error-handling.md`, `security.md`, `privacy.md`, `troubleshooting.md` → Mandatory framework-level standards
17
+ - `structure-audit-2026-05-24.md` → Structure, naming, and folder discipline audit reports
18
+ - `phase1-reference-app-execution-plan.md` → Phase 1 execution plan for the framework team
19
+ - `project-docs.md` → Project documentation policies (governance-focused)
20
+ - `tech-stack.md` → Framework technology stack decisions
21
+
22
+ ---
23
+
24
+ ## Clear Distinction Between root `docs/` and `.enderun/docs/`
25
+
26
+ | Folder | Type | Content Type | Ownership Rule | Example Files |
27
+ |---------------------|-------------------------------|---------------------------------------------------|-----------------------------------------|----------------------------------------|
28
+ | `docs/` (root) | **Project / Product Documentation** | User-facing guides, roadmaps, and action plans provided by Agent Enderun | The project's own `docs/` structure (Documentation Ownership Rule) | getting-started.md, roadmap.md, action-plan-2026.md, README.md |
29
+ | `.enderun/docs/` | **Framework Governance** | Only the framework's internal rules, audits, API contracts, and security policies | Same layer as `.enderun/knowledge/` | api/, structure-audit-*.md, security.md, phase1-*.md |
30
+
31
+ ### Fundamental Rule (Mandatory)
32
+
33
+ - If it is a **framework rule or governance decision** → `.enderun/docs/` or `.enderun/knowledge/`
34
+ - If it is **user-project-specific implementation detail, pattern, or decision** → **User project's own `docs/` folder** (root `docs/` in this repository)
35
+
36
+ This distinction is **fully compliant** with the rule in `.enderun/knowledge/documentation_ownership.md`.
37
+
38
+ **Never** write user-project-specific items such as toaster implementations, approval flow details, component patterns, or technical debt findings here or into `.enderun/knowledge/`.
39
+
40
+ ---
41
+
42
+ ## Related Rules
43
+
44
+ - See `.enderun/knowledge/documentation_ownership.md` (mandatory reading for all agents)
45
+ - See `structure-audit-2026-05-24.md` (items 6.5 and 7)
46
+ - See ENDERUN.md → Core Principles (Framework vs User Project Boundary)
47
+
48
+ ---
49
+
50
+ **This file clarifies the purpose of the `.enderun/docs/` folder and prevents structural confusion.**
@@ -0,0 +1,177 @@
1
+ # Phase 1 Reference Application — Granular Execution Plan (v0.6.5)
2
+
3
+ **Owner:** @manager
4
+ **Status:** APPROVED & ACTIVE (23 May 2026)
5
+ **Goal:** Produce the first production-grade reference application inside `apps/` that proves the entire governance system (Kurumsal CRUD, managerApproval, Hermes, Contract-First, Audit) works in practice.
6
+
7
+ **Critical Rules (Non-Negotiable)**
8
+ - All code lives **only** inside `apps/backend/` and `apps/web/`
9
+ - Never touch `framework-mcp/`, `.enderun/agents/`, root config files
10
+ - Contract-First + Branded Types mandatory
11
+ - Every high-risk action requires explicit `managerApproval`
12
+ - Zero mock data (except 3rd party like Stripe)
13
+ - Full audit logging + Trace ID on every change
14
+
15
+ ---
16
+
17
+ ## Phase 1 Execution Steps (18 Concrete Steps)
18
+
19
+ ### Preparation (Steps 1-2)
20
+
21
+ **Step 1: Activate Execution Plan in Memory**
22
+ - Read current `PROJECT_MEMORY.md`
23
+ - Add new section: "Phase 1 Reference App Execution — Started 2026-05-23"
24
+ - Record Trace ID for this plan (generate via `enderun:trace` or manual ULID)
25
+ - Update Strategic Roadmap to mark Phase 1 as IN_PROGRESS
26
+ - Log this action with `log_agent_action`
27
+
28
+ **Step 2: Workspace Validation**
29
+ - Confirm `apps/` directory does not exist or is empty
30
+ - Verify workspaces in root `package.json` already declare `"apps/*"`
31
+ - Check that `framework-mcp` is buildable (`npm run enderun:build`)
32
+ - Confirm no existing user project code that would conflict
33
+
34
+ ---
35
+
36
+ ### Backend Foundation (Steps 3-8)
37
+
38
+ **Step 3: Create Backend Monorepo Skeleton**
39
+ - `mkdir -p apps/backend/src/{types,db, routes, plugins, utils}`
40
+ - `cd apps/backend && npm init -y`
41
+ - Add required dependencies:
42
+ - fastify, @fastify/cors, @fastify/jwt, kysely, kysely-postgres, zod, @types/node
43
+ - Create `tsconfig.json` (strict, ESM, paths for @/types)
44
+ - Add scripts: `dev`, `build`, `typecheck`, `lint`
45
+
46
+ **Step 4: Define Core Branded Types & Error Hierarchy**
47
+ - Create `apps/backend/src/types/branded.ts` (UserID, RoleID, TraceID, etc.)
48
+ - Create `apps/backend/src/types/domain.ts` (User, Role, Permission)
49
+ - Create `apps/backend/src/types/errors.ts` (DomainError base + specific errors)
50
+ - Update `contract.version.json` (initial version 1.0.0, empty hash)
51
+
52
+ **Step 5: Database Layer (Kysely)**
53
+ - Create `apps/backend/src/db/connection.ts`
54
+ - Create migration folder + first migration (users table with id, email, role, created_at)
55
+ - Create `UserRepository` with findById, findAll, updateRole (with audit fields)
56
+
57
+ **Step 6: Normal CRUD Endpoints (Standard Business Logic)**
58
+ - `POST /users` — create user (standard)
59
+ - `GET /users` — list with pagination + search
60
+ - `GET /users/:id` — detail
61
+ - `PATCH /users/:id` — profile update (non-admin fields)
62
+ - All routes protected by JWT + standard auth plugin
63
+ - Every mutation logs to `apps/backend/logs/` with TraceID
64
+
65
+ **Step 7: High-Risk Admin Operation — Role Upgrade**
66
+ - `PATCH /admin/users/:id/role`
67
+ - Payload must contain: `isHighRiskAdminAction: true`, `newRole: 'SuperAdmin'`
68
+ - Backend **must refuse** unless valid `managerApproval` object is present in headers/body
69
+ - `managerApproval` = { traceId, approvedBy: '@manager', timestamp, signature (simple hash for v1), reason }
70
+ - Create `plugins/managerApproval.ts` validator
71
+ - On success: update role + write full before/after audit record to `logs/admin-actions.jsonl`
72
+
73
+ **Step 8: Contract Versioning & Verification**
74
+ - After any type change, run contract hash update
75
+ - Store `contract.version.json` with hash of all exported types
76
+ - Add endpoint `GET /contract` that returns current version + hash
77
+
78
+ ---
79
+
80
+ ### Frontend Foundation (Steps 9-13)
81
+
82
+ **Step 9: Create Frontend Monorepo Skeleton**
83
+ - `mkdir -p apps/web/src/{components/ui, pages, hooks, types, lib}`
84
+ - `cd apps/web && npm create vite@latest . -- --template react-ts`
85
+ - Install: @vitejs/plugin-react, panda-css, zustand (if needed), lucide-react (icons only)
86
+ - Configure Panda CSS (use root `panda.config.ts` or local copy)
87
+ - Set up `styled-system/` generation
88
+
89
+ **Step 10: UI Component System (Zero Library + Composition)**
90
+ - Create inside `apps/web/src/components/ui/`:
91
+ - `Button.tsx` (compound: Button + Button.Icon + Button.Loading)
92
+ - `Modal.tsx` (with slot for header/body/footer)
93
+ - `Table.tsx` (with Row, Cell composition)
94
+ - `FormField.tsx`
95
+ - All components use Panda CSS + strict accessibility props
96
+ - Enforce 44x44px touch targets, focus rings, ARIA
97
+
98
+ **Step 11: Type Contract Sync (Frontend Side)**
99
+ - Copy or generate branded types from backend into `apps/web/src/types/`
100
+ - Create script that fails build if `contract.version.json` hash mismatches
101
+ - Use same branded types on client (UserID etc.)
102
+
103
+ **Step 12: Normal User Pages**
104
+ - `/users` — list (Table component + pagination)
105
+ - `/users/:id` — detail + edit form (profile only)
106
+ - Use hooks: `useListPage`, `useDetailPage` (blueprint pattern)
107
+ - All data fetching goes through typed API client
108
+
109
+ **Step 13: High-Risk Role Change UI**
110
+ - On user detail page, show "Upgrade to SuperAdmin" button (only for authorized)
111
+ - Button opens `SecurityApprovalModal`
112
+ - Modal shows:
113
+ - Risk warning
114
+ - Reason input
115
+ - "Request Manager Approval" button → triggers Hermes message to @manager
116
+ - After approval token received → submits the high-risk PATCH with `managerApproval` payload
117
+ - On success: shows audit trail + success banner
118
+
119
+ ---
120
+
121
+ ### Integration & Governance Proof (Steps 14-18)
122
+
123
+ **Step 14: Hermes Integration**
124
+ - Implement `send_agent_message` usage from frontend (via backend proxy or direct if MCP available)
125
+ - Scenario: Frontend requests briefing for role change → @manager responds with signed approval
126
+ - Log all Hermes messages under `.enderun/messages/`
127
+
128
+ **Step 15: Full Audit & Logging System**
129
+ - Backend writes structured JSONL logs for every mutation
130
+ - High-risk actions additionally write to dedicated `admin-audit.log`
131
+ - Trace ID propagated from @manager briefing all the way to DB and UI
132
+
133
+ **Step 16: Contract Integrity Gate**
134
+ - Add Vitest test that compares backend `contract.version.json` hash vs frontend copied types
135
+ - Fail CI if drift detected
136
+
137
+ **Step 17: Professionalization Checkpoints (Frontend)**
138
+ - All components pass manual WCAG 2.2 AA checklist (documented)
139
+ - Performance budgets verified (LCP < 2.5s, bundle < 250KB)
140
+ - Minimum 70% component test coverage
141
+
142
+ **Step 18: Final Governance Validation**
143
+ - @manager performs full walkthrough:
144
+ 1. Normal CRUD works without special approval
145
+ 2. High-risk role upgrade is **blocked** until managerApproval present
146
+ 3. Hermes message was sent and processed
147
+ 4. Full audit trail exists in logs
148
+ 5. Contract version is consistent
149
+ - Update `PROJECT_MEMORY.md` — mark Phase 1 COMPLETE
150
+ - Record maturity increase for @backend and @frontend
151
+ - Update Risk Dashboard: "No Production-Grade Reference Application" → CLOSED
152
+
153
+ ---
154
+
155
+ ## Success Criteria (Definition of Done for Phase 1)
156
+
157
+ - A developer can run `npm run dev --workspace=backend` and `npm run dev --workspace=web`
158
+ - Can create user via UI, then attempt role upgrade
159
+ - Role upgrade fails without @manager approval
160
+ - After simulated approval, role changes and audit log is written
161
+ - Hermes message appears in `.enderun/messages/`
162
+ - `contract.version.json` is maintained and verified
163
+ - Zero lint errors, all TypeScript strict
164
+ - All high-risk rules from `manager.md` followed
165
+
166
+ ---
167
+
168
+ ## Risk Mitigation During Execution
169
+
170
+ - If any step takes > 2 sessions → split further and update memory
171
+ - If frontend composition patterns feel weak → pause and reinforce @frontend agent first
172
+ - Every major decision must be recorded in CRITICAL DECISIONS section of PROJECT_MEMORY.md
173
+
174
+ **Next Action After This Plan:** Execute Step 1 immediately.
175
+
176
+ ---
177
+ *This document is the single source of truth for Phase 1 execution. Every step must be checked off in PROJECT_MEMORY.md before moving to the next.*
@@ -0,0 +1,72 @@
1
+ # Structure & Naming Audit Report
2
+
3
+ **Project:** Agent Enderun
4
+ **Date:** 24 May 2026
5
+ **Auditor:** @manager (AI-assisted)
6
+ **Scope:** File/folder naming + overall structural quality (excluding apps/, only governance and MCP layer)
7
+
8
+ ---
9
+
10
+ ## 1. Executive Summary
11
+
12
+ **Overall Score:** 7.2 / 10
13
+
14
+ The project is moving toward an **enterprise-scale manageable structure**, especially with the improvements made in May 2026. However, there are still significant gaps in **naming consistency**, **discoverability**, and **folder discipline**.
15
+
16
+ **Strongest Areas:**
17
+ - Clear separation between `.enderun/` and `framework-mcp/` layers
18
+ - Knowledge files mostly follow consistent `kebab-case`
19
+ - Newly created `live-tests/` structure is clean and scalable
20
+
21
+ **Most Critical Weaknesses:**
22
+ - Core "brain" files (`PROJECT_MEMORY.md`, `BRAIN_DASHBOARD.md`) use mixed UPPERCASE + snake_case
23
+ - Many important folders lack README / INDEX files
24
+ - `.enderun/messages/` contains a mix of old and new test messages
25
+ - Content clutter in the `blueprints/` folder
26
+
27
+ ---
28
+
29
+ ## 2. Naming Consistency
30
+
31
+ ### Good Practices
32
+ - Agent files: `manager.md`, `backend.md`, `git.md` → **consistent lowercase**
33
+ - Knowledge files: `hermes_protocol.md`, `enterprise_project_adaptation.md` → **nearly perfect kebab-case**
34
+ - MCP tool files: `contract.ts`, `memory.ts`, `hermes_live_test_guidelines.md` → good
35
+
36
+ ### Issues Found
37
+
38
+ | File / Folder | Problem | Recommendation | Priority |
39
+ |----------------------------------------|----------------------------------------------|-----------------------------------------|----------|
40
+ | `PROJECT_MEMORY.md` | UPPERCASE + underscore | `project-memory.md` | High |
41
+ | `BRAIN_DASHBOARD.md` | UPPERCASE + underscore | `brain-dashboard.md` | High |
42
+ | `2026-05-23-manager-to-backend-....json` | Dated flat message files | `messages/archive/2026-05-23/...` | High |
43
+ | `blueprints/backend/errors/domain-error.ts` + `blueprint.json` | Both TS and JSON in same folder | `blueprints/backend/errors/` + `config/` | Medium |
44
+
45
+ **Conclusion:** Naming is ~80% consistent. The biggest problem is special treatment given to "core brain files".
46
+
47
+ ---
48
+
49
+ ## 3. Folder Structure Evaluation
50
+
51
+ ### Strong Points
52
+ - `.enderun/` → Governance layer (agents, knowledge, memory, rules)
53
+ - `framework-mcp/src/tools/` → MCP tools are modular and domain-separated (excellent)
54
+ - `.enderun/messages/live-tests/` → New structure is very clean and scalable
55
+
56
+ ### Weaknesses and Risks
57
+ 1. **Missing README / Discoverability**
58
+ 2. Mixed old and new test messages in `.enderun/messages/`
59
+ 3. Content disorder in `blueprints/`
60
+
61
+ ---
62
+
63
+ ## 4. Recommendations (Priority Order)
64
+
65
+ 1. Rename core brain files to lowercase kebab-case.
66
+ 2. Add README.md to every important folder.
67
+ 3. Archive old test messages under `messages/archive/`.
68
+ 4. Enforce strict blueprint discipline (no empty folders).
69
+
70
+ **Overall:** The governance layer is structurally sound but needs naming and documentation hygiene improvements to reach true enterprise maturity.
71
+
72
+ **Last Updated:** 24 May 2026
@@ -0,0 +1,22 @@
1
+ # Knowledge Base
2
+
3
+ This directory is the **permanent enterprise knowledge** repository for Agent Enderun agents.
4
+
5
+ ## Content Rules
6
+ - File names **must** be in kebab-case (`hermes-protocol.md`, `enterprise-project-adaptation.md`).
7
+ - Every file must contain a clear title and "Version / Owner / Last Updated" metadata.
8
+ - Knowledge should be as **practical and actionable** as possible (not just theory).
9
+
10
+ ## Important Files
11
+ - `enterprise_project_adaptation.md` → Enterprise project entry protocol (EPDP)
12
+ - `enterprise_frontend_adaptation.md` → Enterprise adaptation rules for frontend
13
+ - `hermes_protocol.md` → Inter-agent communication standard
14
+ - `manager_authority_audit_enforcement.md` → @manager authority audit rules
15
+ - `hermes_live_test_guidelines.md` → Hermes test program
16
+
17
+ ## Usage
18
+ Agents must search this directory first when conducting research or making decisions (using the `search_knowledge_base` tool).
19
+
20
+ Newly discovered important patterns or rules must be written here.
21
+
22
+ **Last Updated:** 24 May 2026
@@ -0,0 +1,118 @@
1
+ # Enterprise Database Governance and Performance Guidelines (DBA SOP)
2
+
3
+ **Version:** v0.6.5 | **Ownership:** @backend & @dba Security Framework
4
+
5
+ This document is the constitutional database ruleset establishing **Zero-Downtime DDL (schema migrations)**, **maximum query performance (Index Tuning)**, and **deadlock prevention strategies (Lock Management)** in applications running under the PostgreSQL + Kysely architecture. `@backend` executes these rules with 0 error tolerance when writing code, and `@analyst` actively audits them during code review.
6
+
7
+ ---
8
+
9
+ ## ⚡ 1. INDEX OPTIMIZATION LAWS (INDEX TUNING)
10
+
11
+ To ensure that queries do not exhaust the database and can respond to thousands of requests per second, index design cannot be left to chance.
12
+
13
+ ### 1.1 Foreign Key Index Obligation
14
+ * **Rule:** For every Foreign Key (FK) column defined, **it is mandatory to create a corresponding index**.
15
+ * **Rationale:** Prevents sequential scans on the target table during `JOIN` operations and when deleting data from the parent table (`ON DELETE CASCADE`).
16
+ * **Kysely/SQL Pattern:**
17
+ ```typescript
18
+ // Inside the migration file
19
+ await db.schema.createIndex('idx_orders_user_id')
20
+ .on('orders')
21
+ .column('user_id')
22
+ .execute();
23
+ ```
24
+
25
+ ### 1.2 Concurrent Indexing
26
+ * **Rule:** All indexes created on production databases **must be created using the `CONCURRENTLY` keyword**.
27
+ * **Rationale:** Standard index creation locks the target table completely for write operations (`ShareLock`). `CONCURRENTLY` builds the index in the background without locking the table.
28
+ * **Migration Rule:** When creating indexes concurrently, the migration process must run outside of a database transaction. In Kysely, this operation must be run `transaction-free`.
29
+
30
+ ### 1.3 Partial & Composite Indexes
31
+ * **Rule:** **Partial Indexes** must be used on tables using soft deletes (`deleted_at IS NOT NULL`) or when queries filter by a specific status.
32
+ * **Kysely Pattern:**
33
+ ```typescript
34
+ // An extremely fast and small index that scans only active records
35
+ await db.schema.createIndex('idx_active_users_email')
36
+ .on('users')
37
+ .column('email')
38
+ .where(sql`deleted_at IS NULL`)
39
+ .execute();
40
+ ```
41
+ * **Rule 2:** When creating composite indexes for multi-column searches like `WHERE a = x AND b = y`, the **column with the highest selectivity (high cardinality) must be placed on the far left**.
42
+
43
+ ---
44
+
45
+ ## 🔒 2. DATABASE LOCK MANAGEMENT (LOCK MANAGEMENT)
46
+
47
+ Incorrect lock management leads to connection pool exhaustion within seconds, causing a complete system crash (cascading failure).
48
+
49
+ ### 2.1 Transaction Boundaries and Golden Rules
50
+ 1. **Zero Network Inside TX:** While a database transaction (`db.transaction()`) is active, **external API calls, sending emails, or file read/write operations are strictly forbidden**. A 1-second network latency causes locks in the database to be held for that second, clogging the entire system.
51
+ 2. **Keep it Short Principle:** Transactions must only contain database write operations and must be `committed` as quickly as possible.
52
+
53
+ ### 2.2 Deadlock Prevention and Smart Query Design
54
+ * **Rule:** The use of `SELECT ... FOR UPDATE` (Row Lock) is forbidden except in high-urgency scenarios. When its use is mandatory, the query must be restricted with **`NOWAIT`** or **`SKIP LOCKED`** parameters to avoid entering the queue and causing deadlocks.
55
+ * **Kysely Pattern:**
56
+ ```typescript
57
+ // Instead of waiting in a queue and locking the system, throw an error or skip if locked
58
+ const job = await db.selectFrom('jobs')
59
+ .selectAll()
60
+ .where('status', '=', 'PENDING')
61
+ .limit(1)
62
+ .forUpdate()
63
+ .skipLocked() // OR .noWait()
64
+ .executeTakeFirst();
65
+ ```
66
+
67
+ ### 2.3 Timeout Safety
68
+ Lock timeout parameters must be set before every session or heavy migration. This ensures that if a lock accumulation occurs in the background, the transaction cancels itself instead of locking up the system.
69
+ ```sql
70
+ SET statement_timeout = '15s';
71
+ SET lock_timeout = '5s';
72
+ ```
73
+
74
+ ---
75
+
76
+ ## 🛡️ 3. SAFE SCHEMA TRANSITION LAWS (SAFE MIGRATIONS - DDL)
77
+
78
+ To ensure zero-downtime during schema migrations on production environments, the following templates must be applied:
79
+
80
+ ### 3.1 NOT NULL Column Addition Procedure
81
+ Adding a column containing a `NOT NULL` constraint directly to a production table causes PostgreSQL to lock the entire table. The safe procedure is:
82
+ 1. Add the column as **nullable**.
83
+ 2. Update the data in the background with default values (in batches).
84
+ 3. Add the `NOT NULL` constraint to the column (this operation no longer creates a lock).
85
+
86
+ ### 3.2 Breaking Column/Table Changes - "Expand & Contract"
87
+ Renaming a column or changing its data type directly on a live system is strictly forbidden. Instead, follow these 5 steps:
88
+ ```
89
+ [Deployment 1 - EXPAND]
90
+ Add the new column. Start dual-writing in the codebase (write to both old and new columns).
91
+
92
+ [Deployment 2 - BACKFILL]
93
+ Migrate legacy data from the old column to the new column in the background (Batch Update).
94
+
95
+ [Deployment 3 - READ SWITCH]
96
+ Redirect all read requests in the codebase to the new column.
97
+
98
+ [Deployment 4 - STOP DUAL-WRITE]
99
+ Completely stop writing to the old column.
100
+
101
+ [Deployment 5 - CONTRACT]
102
+ Delete the old column from the database (Drop Column).
103
+ ```
104
+
105
+ ### 3.3 Adding Constraints Safely
106
+ To prevent table locks when adding `CHECK` or `FOREIGN KEY` constraints to large tables:
107
+ 1. Add the constraint as `NOT VALID` (bypasses scanning legacy data, returns immediately).
108
+ 2. Then, validate the constraint in the background by running the `VALIDATE CONSTRAINT` command concurrently.
109
+
110
+ ---
111
+
112
+ ## 🕵️ 4. AUTOMATED QA GATE CHECKLIST
113
+
114
+ `@analyst` scans the database schema and queries automatically during code review against these rules:
115
+ * [ ] For every new `table.foreign()` definition, is a corresponding `createIndex()` defined?
116
+ * [ ] Is `.forUpdate()` used in any `selectFrom` query without `.skipLocked()` or `.noWait()` written next to it?
117
+ * [ ] Is there any `alterTable().renameColumn()` or direct destructive `dropColumn()` in migration files? (Expand/Contract audit).
118
+ * [ ] Is `CONCURRENTLY` used in index additions on large tables?