atabey 0.0.14 → 0.0.15

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 (71) hide show
  1. package/PRIVACY.md +8 -14
  2. package/README.md +163 -14
  3. package/bin/cli.js +72 -5
  4. package/dist/framework-mcp/src/index.js +76 -3
  5. package/dist/framework-mcp/src/index.js.map +1 -1
  6. package/dist/framework-mcp/src/tools/messaging/approve_operation.d.ts +8 -8
  7. package/dist/framework-mcp/src/tools/messaging/approve_operation.js +11 -11
  8. package/dist/framework-mcp/src/tools/messaging/approve_operation.js.map +1 -1
  9. package/dist/framework-mcp/src/tools/messaging/ask_human.d.ts +8 -8
  10. package/dist/framework-mcp/src/tools/messaging/ask_human.js +8 -8
  11. package/dist/framework-mcp/src/tools/observability/check_ports.d.ts +1 -0
  12. package/dist/framework-mcp/src/tools/observability/check_ports.js +21 -7
  13. package/dist/framework-mcp/src/tools/observability/check_ports.js.map +1 -1
  14. package/dist/framework-mcp/src/tools/shell/run_command.js +138 -92
  15. package/dist/framework-mcp/src/tools/shell/run_command.js.map +1 -1
  16. package/dist/framework-mcp/src/utils/auth.js +4 -4
  17. package/dist/framework-mcp/src/utils/auth.js.map +1 -1
  18. package/dist/framework-mcp/src/utils/discipline.js +1 -1
  19. package/dist/framework-mcp/src/utils/discipline.js.map +1 -1
  20. package/dist/framework-mcp/src/utils/human-in-loop.js +1 -1
  21. package/dist/framework-mcp/src/utils/human-in-loop.js.map +1 -1
  22. package/dist/framework-mcp/src/utils/loop-detector.js +3 -3
  23. package/dist/framework-mcp/src/utils/loop-detector.js.map +1 -1
  24. package/dist/framework-mcp/src/utils/quality.js +4 -3
  25. package/dist/framework-mcp/src/utils/quality.js.map +1 -1
  26. package/dist/framework-mcp/src/utils/silent-router.d.ts +4 -2
  27. package/dist/framework-mcp/src/utils/silent-router.js +35 -9
  28. package/dist/framework-mcp/src/utils/silent-router.js.map +1 -1
  29. package/dist/framework-mcp/tests/tools/observability/check_ports.test.js +26 -12
  30. package/dist/framework-mcp/tests/tools/observability/check_ports.test.js.map +1 -1
  31. package/dist/framework-mcp/tests/tools/shell/run_command.test.js +38 -15
  32. package/dist/framework-mcp/tests/tools/shell/run_command.test.js.map +1 -1
  33. package/dist/src/cli/commands/init.js +14 -7
  34. package/dist/src/cli/commands/init.js.map +1 -1
  35. package/dist/src/cli/commands/mcp.js +3 -1
  36. package/dist/src/cli/commands/mcp.js.map +1 -1
  37. package/dist/src/cli/commands/script.js +8 -1
  38. package/dist/src/cli/commands/script.js.map +1 -1
  39. package/dist/src/modules/engines/agent-executor.js +11 -1
  40. package/dist/src/modules/engines/agent-executor.js.map +1 -1
  41. package/dist/src/modules/engines/agent-loop.d.ts +5 -5
  42. package/dist/src/modules/engines/agent-loop.js +5 -5
  43. package/dist/src/modules/engines/evaluation-engine.d.ts +12 -2
  44. package/dist/src/modules/engines/evaluation-engine.js +76 -9
  45. package/dist/src/modules/engines/evaluation-engine.js.map +1 -1
  46. package/dist/src/shared/pii.js +1 -1
  47. package/dist/src/shared/pii.js.map +1 -1
  48. package/dist/src/shared/storage.d.ts +43 -0
  49. package/dist/src/shared/storage.js +1 -1
  50. package/dist/src/shared/storage.js.map +1 -1
  51. package/dist/tests/modules/engines/agent-executor.test.js +1 -1
  52. package/dist/tests/modules/engines/agent-executor.test.js.map +1 -1
  53. package/framework-mcp/dist/dashboard/assets/{index-B2mYld0c.js → index-B_rK57vi.js} +17 -17
  54. package/framework-mcp/dist/dashboard/index.html +1 -1
  55. package/framework-mcp/dist/framework-mcp/src/index.js +76 -3
  56. package/framework-mcp/dist/framework-mcp/src/tools/messaging/approve_operation.js +11 -11
  57. package/framework-mcp/dist/framework-mcp/src/tools/messaging/ask_human.js +8 -8
  58. package/framework-mcp/dist/framework-mcp/src/tools/observability/check_ports.js +21 -7
  59. package/framework-mcp/dist/framework-mcp/src/tools/shell/run_command.js +138 -92
  60. package/framework-mcp/dist/framework-mcp/src/utils/auth.js +4 -4
  61. package/framework-mcp/dist/framework-mcp/src/utils/discipline.js +1 -1
  62. package/framework-mcp/dist/framework-mcp/src/utils/human-in-loop.js +1 -1
  63. package/framework-mcp/dist/framework-mcp/src/utils/loop-detector.js +3 -3
  64. package/framework-mcp/dist/framework-mcp/src/utils/quality.js +4 -3
  65. package/framework-mcp/dist/framework-mcp/src/utils/silent-router.js +35 -9
  66. package/framework-mcp/dist/src/modules/engines/evaluation-engine.js +169 -0
  67. package/framework-mcp/dist/src/shared/pii.js +1 -1
  68. package/framework-mcp/dist/src/shared/storage.js +1 -1
  69. package/framework-mcp/package.json +1 -1
  70. package/mcp.json +3 -2
  71. package/package.json +3 -4
package/PRIVACY.md CHANGED
@@ -93,14 +93,14 @@ DataRetention.eraseAllData("KVKK-RIGHT-TO-ERASURE");
93
93
 
94
94
  ### 4. Data Portability (KVKK Art. 11 / GDPR Art. 20)
95
95
 
96
- All stored data is exportable:
96
+ All stored operational data and metrics are inspectable:
97
97
 
98
98
  ```bash
99
- # Export audit logs
100
- atabey gateway stats
99
+ # View agent statuses, token usage, and cost distributions
100
+ atabey status
101
101
 
102
- # Export all data
103
- atabey kvkk:export
102
+ # Run full health and compliance checks
103
+ atabey check
104
104
  ```
105
105
 
106
106
  ### 5. Data Processing Records (KVKK Art. 4 / GDPR Art. 30)
@@ -129,16 +129,10 @@ Every data processing operation is logged in the audit trail:
129
129
  ## 📝 CLI Commands
130
130
 
131
131
  ```bash
132
- # Check current retention status
133
- atabey kvkk:status
134
-
135
- # Export data inventory
136
- atabey kvkk:export
137
-
138
- # Erase all data (with confirmation)
139
- atabey kvkk:erase-all
132
+ # View agent status, token usage, and cost distribution
133
+ atabey status
140
134
 
141
- # Run compliance audit
135
+ # Run compliance, health, and security checks
142
136
  atabey check
143
137
  ```
144
138
 
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # [GOV] Agent Atabey — MCP-Powered AI Governance & Autonomous Orchestration
1
+ # [GOV] Agent Atabey — MCP-Powered AI Governance & Multi-Agent Workflow Layer for AI Coding Assistants
2
2
 
3
3
  [![Version](https://img.shields.io/badge/Version-v0.0.15-blue.svg)](https://github.com/ysf-bkr/atabey)
4
4
  [![npm](https://img.shields.io/npm/v/atabey)](https://www.npmjs.com/package/atabey)
@@ -38,6 +38,9 @@ You (@backend): "Create a user login service with JWT authentication"
38
38
 
39
39
  **No separate terminal needed. No CLI commands for daily use.** Just chat with your AI and use `@agent` syntax.
40
40
 
41
+ > [!NOTE]
42
+ > **Execution Context:** The LLM inference/execution is handled entirely inside the developer's active AI interface (such as Claude Code or Cursor). Atabey acts as the context injector and policy engine, silently evaluating prompts, routing instructions, and checking output code against quality guidelines.
43
+
41
44
  ---
42
45
 
43
46
  ## 📋 Table of Contents
@@ -77,6 +80,7 @@ Atabey generates an `mcp.json` config. Point your AI assistant to it:
77
80
  "command": "npx",
78
81
  "args": ["-y", "atabey-mcp"],
79
82
  "env": {
83
+ "MCP_TRANSPORT": "stdio",
80
84
  "ATABEY_PROJECT_ROOT": "/path/to/your/project"
81
85
  }
82
86
  }
@@ -86,8 +90,10 @@ Atabey generates an `mcp.json` config. Point your AI assistant to it:
86
90
 
87
91
  **Gemini CLI:**
88
92
  ```bash
93
+ # Stdio mode (local, single user)
89
94
  gemini config set mcpServers.atabey.command "npx"
90
95
  gemini config set mcpServers.atabey.args "[\"-y\", \"atabey-mcp\"]"
96
+ gemini config set mcpServers.atabey.env "{\"MCP_TRANSPORT\": \"stdio\", \"ATABEY_PROJECT_ROOT\": \"/path/to/your/project\"}"
91
97
  ```
92
98
 
93
99
  **Cursor:**
@@ -97,7 +103,10 @@ gemini config set mcpServers.atabey.args "[\"-y\", \"atabey-mcp\"]"
97
103
  "mcpServers": {
98
104
  "atabey": {
99
105
  "command": "npx",
100
- "args": ["-y", "atabey-mcp"]
106
+ "args": ["-y", "atabey-mcp"],
107
+ "env": {
108
+ "MCP_TRANSPORT": "stdio"
109
+ }
101
110
  }
102
111
  }
103
112
  }
@@ -242,6 +251,9 @@ npx atabey init gemini
242
251
 
243
252
  ## 13 Specialized Agents
244
253
 
254
+ > [!NOTE]
255
+ > Each agent listed below represents a specialized prompt and rule-template context injected via the MCP server. The actual reasoning and file modification are performed by the developer's active client AI interface using the instructions supplied by these agents.
256
+
245
257
  | Agent | Tier | Role | Freelancer | Team | Enterprise |
246
258
  |-------|------|------|:----------:|:----:|:----------:|
247
259
  | **@manager** | Supreme | Orchestration, governance, quality gate | ✅ | ✅ | ✅ |
@@ -265,7 +277,7 @@ npx atabey init gemini
265
277
  ### 1. Deterministic Quality Gate
266
278
  No agent can push code directly to production. All outputs pass through AST analysis (compliance), linting, and unit tests. Failed code triggers an automatic 3-attempt retry loop.
267
279
 
268
- ### 2. Autonomous Vector Memory
280
+ ### 2. Persistent Vector Memory
269
281
  Project context, contracts, and past tasks are stored locally via `better-sqlite3` using TF-IDF semantic search (cosine similarity). Agents search past architectural decisions.
270
282
 
271
283
  ### 3. Hermes Message Broker
@@ -274,6 +286,9 @@ Agents communicate asynchronously via a SQLite-backed message queue. A file-base
274
286
  ### 4. Risk Engine (Human-in-the-Loop — In-Chat Approval)
275
287
  Operations containing `DROP`, `DELETE`, `TRUNCATE`, or secret manipulation are flagged. Execution is blocked until human approval.
276
288
 
289
+ > [!NOTE]
290
+ > **Heuristic Detection:** The Risk Engine relies on deterministic keyword and path-pattern heuristics (e.g., matching SQL command strings) rather than complex machine learning models to identify and block high-risk operations.
291
+
277
292
  **In-Chat Approval (no terminal switch needed):**
278
293
  When an operation is blocked, the AI is instructed to call the `approve_operation` MCP tool:
279
294
  ```
@@ -298,7 +313,7 @@ Claude Code, Gemini CLI, Cursor, Codex CLI, Antigravity CLI — automatic agent
298
313
  Node.js, Go, Java, Python, .NET — automatic scaffolding based on backend language selection.
299
314
 
300
315
  ### 9. Multi-User Distributed Lock Registry
301
- When multiple developers work on the same repository, their autonomous agents might attempt to modify the same files simultaneously. Atabey implements a Git-aware distributed locking mechanism (`DistributedLock`). It dynamically identifies the lock owner using `git config user.name` and blocks other processes from mutating the locked resources until released or expired, preventing merge conflicts and race conditions.
316
+ When multiple developers work on the same repository, their contextual agents might attempt to modify the same files simultaneously. Atabey implements a Git-aware distributed locking mechanism (`DistributedLock`). It dynamically identifies the lock owner using `git config user.name` and blocks other processes from mutating the locked resources until released or expired, preventing merge conflicts and race conditions.
302
317
 
303
318
  ### 10. Multi-Client MCP Support (Stdio + HTTP/SSE)
304
319
  Atabey supports two transport modes:
@@ -385,11 +400,11 @@ Atabey automatically classifies data into security levels:
385
400
 
386
401
  Data portability (KVKK Art. 11 / GDPR Art. 20):
387
402
  ```bash
388
- # Export all data
389
- atabey kvkk:export
403
+ # View agent statuses, token usage, and cost distributions
404
+ atabey status
390
405
 
391
- # Export audit logs
392
- atabey gateway stats
406
+ # Run full health and compliance checks
407
+ atabey check
393
408
  ```
394
409
 
395
410
  ### 15. Adapter-Skill System
@@ -499,12 +514,24 @@ atabey mcp install Generate mcp.json config for AI integration
499
514
  atabey dashboard [port] Open web dashboard (default: 5858)
500
515
  atabey status Show agent statuses and costs
501
516
  atabey check Full health and compliance check
502
- atabey orchestrate Start autonomous orchestration loop
517
+ atabey orchestrate Start orchestration workflow loop
503
518
  atabey approve <traceId> Approve a blocked high-risk task (terminal alternative)
504
519
  atabey hitl answer "<text>" Answer a pending ask_human question
505
520
  atabey @agent "task" Send task directly to an agent
506
521
  ```
507
522
 
523
+ ### `atabey init [adapter]` Options
524
+
525
+ | Option | Values | Description |
526
+ |---|---|---|
527
+ | `[adapter]` | `gemini`, `claude`, `cursor`, `grok`, `codex`, `local`, `antigravity-cli` | The target AI platform/client for initialization. |
528
+ | `--profile` | `freelancer`, `team`, `enterprise` | Preset agent group layout and governance complexity. |
529
+ | `--focus` | `fullstack`, `backend`, `frontend`, `mobile`, `mobile-fullstack` | Optimize active agents and templates for the project type. |
530
+ | `--lang` | `tr`, `en` | Set the language for constitution (`ATABEY.md`) and standard operating procedures. |
531
+ | `--unified` | *None (Flag)* | Place all agent instruction files under a single `.agents/` directory with native client links. |
532
+ | `--yes` | *None (Flag)* | Run in non-interactive mode using default or provided parameters. |
533
+ | `--dryRun` | *None (Flag)* | Simulate the initialization run without writing any files or folders to the workspace. |
534
+
508
535
  > **In-chat alternative:** Use `approve_operation` MCP tool directly in your AI CLI chat — no terminal switch needed.
509
536
 
510
537
  Full command list: see `atabey help` or [ARCHITECTURE.md](ARCHITECTURE.md)
@@ -538,7 +565,6 @@ Full command list: see `atabey help` or [ARCHITECTURE.md](ARCHITECTURE.md)
538
565
 
539
566
  ---
540
567
 
541
-
542
568
  ## ✅ Implemented Governance Features
543
569
 
544
570
  > These features were previously listed as "Blind Spots" but are now fully implemented:
@@ -553,11 +579,131 @@ Full command list: see `atabey help` or [ARCHITECTURE.md](ARCHITECTURE.md)
553
579
 
554
580
  ---
555
581
 
582
+ ## 🔍 Detailed Feature Analysis
583
+
584
+ ### Auto-Rollback & Rollback Mechanism
585
+ `framework-mcp/src/utils/auto-rollback.ts`
586
+
587
+ **How It Works:**
588
+ ```
589
+ [AI write_file/replace_text/patch_file call]
590
+
591
+ ├── 1. Pre-Write Snapshot → Original file content saved (SnapshotManager)
592
+ ├── 2. Tool executes → File is written
593
+ ├── 3. Post-Write Validation → rules-engine.ts GOV scan
594
+ │ ├── ✅ Clean → Allow, clear snapshot
595
+ │ └── ❌ Violation (any type, console.log, secret, copyleft) →
596
+ │ ├── Original file restored
597
+ │ ├── New file deleted
598
+ │ └── REGENERATE instruction sent to AI:
599
+ │ "⛔ AI Output Blocked – Governance Violation
600
+ │ 🔴 No `any` Type (file.ts:5)
601
+ │ Fix: Replace `any` with `unknown`"
602
+ └── Dashboard WS → rollback_violation event
603
+ ```
604
+
605
+ **Detected Violations:**
606
+ | Violation | Severity | Detection |
607
+ |-----------|----------|-----------|
608
+ | `any` type usage | 🔴 CRITICAL | Regex: `: any\b` |
609
+ | `console.log`/`.error`/`.warn`/`.debug` | 🔴 CRITICAL | Regex (exempts logger.ts) |
610
+ | Hardcoded API Key (sk-, ghp_, AIza) | 🟠 HIGH | Regex pattern |
611
+ | Hardcoded GitHub Token | 🟠 HIGH | `ghp_` pattern |
612
+ | Copyleft license violation | 🔴 CRITICAL | `license-scanner.ts` |
613
+
614
+ **Test Status:** ✅ `auto-rollback.test.ts` — 14 tests, 228 lines, all scenarios covered.
615
+
616
+ **Critical Assessment:** Working. The `buildRegenerateInstruction()` method tells the AI exactly what it did wrong and how to fix it. This is far more valuable than simple blocking.
617
+
618
+ ---
619
+
620
+ ### Specialty Memory (Agent Learning Mechanism)
621
+ `src/modules/engines/evaluation-engine.ts`
622
+
623
+ | Status | Detail |
624
+ |--------|--------|
625
+ | ✅ **Error Learning** | Compliance/lint/test failure → `updateSpecialtyMemory()` writes to `.atabey/memory/specialties/<agent>.md` |
626
+ | ❌ **Success Learning** | No mechanism to extract lessons from successful tasks |
627
+ | ❌ **Auto-Injection** | `readLearnedConventions()` exists but is not automatically injected into AI context |
628
+ | ⚠️ **Learning Opportunity** | Agent never asked "What did I learn from this task?" on completion |
629
+
630
+ **Current Flow:**
631
+ ```
632
+ Task → Evaluation → Any errors?
633
+ ├── Yes → `updateSpecialtyMemory(agent, "Compliance Violations Detected...")`
634
+ └── No → Nothing saved (❌)
635
+ ```
636
+
637
+ **Desired Flow:**
638
+ ```
639
+ Task → Evaluation →
640
+ ├── Error → Save error lesson
641
+ └── Success → Save success lesson: "agent/service pattern was used successfully"
642
+ ```
643
+
644
+ ---
645
+
646
+ ### Token/Cost Tracking (FinOps)
647
+ `framework-mcp/src/utils/finops.ts`
648
+
649
+ | Feature | Status |
650
+ |---------|--------|
651
+ | ✅ Per-agent token tracking | Every MCP tool call logged via `Metrics.logUsage()` |
652
+ | ✅ Monthly budget | `ATABEY_BUDGET_MONTHLY` env for USD-based limit |
653
+ | ✅ Per-agent budget | `ATABEY_BUDGET_AGENT_MAX` for agent-based limit |
654
+ | ✅ Auto-shutdown | MCP middleware returns error when budget exceeded |
655
+ | ✅ Alert thresholds | 50/80/90/100% warning levels |
656
+ | ✅ Dashboard panel | FinOpsPanel.tsx with live visualization |
657
+ | ✅ API endpoint | `GET /api/metrics` — agent/action level detail |
658
+ | ❌ **Weekly Summary** | `atabey status` output does not provide a weekly rollup overview |
659
+
660
+ **Usage:** `framework-mcp/src/index.ts` (lines 150-153) calls `Metrics.logUsage()` on every tool call.
661
+
662
+ ---
663
+
664
+ ### KVKK/GDPR Data Privacy
665
+ `src/shared/pii.ts`
666
+
667
+ | Pattern | Mask | Test |
668
+ |---------|------|------|
669
+ | Email | `***@***` | ✅ |
670
+ | Phone (+90 TR, international) | `***-***-****` | ✅ |
671
+ | TC ID (11 digits) | `***********` | ✅ |
672
+ | API Key (OpenAI, GitHub, Google) | `***-REDACTED-***` | ✅ |
673
+ | JWT Token | `***-JWT-REDACTED-***` | ✅ |
674
+ | IP (IPv4, IPv6) | `***.***.***.***` | ✅ |
675
+ | Credit Card (AMEX included) | `****-****-****-****` | ✅ |
676
+ | IBAN | `****-IBAN-REDACTED-****` | ✅ |
677
+ | Date of Birth | `**/**/****` | ✅ |
678
+ | SSN (US) | `***-**-****` | ✅ |
679
+ | Password/Secret fields | `***-REDACTED-***` | ✅ |
680
+
681
+ **Layered Protection:**
682
+ 1. **MCP Middleware** — `maskToolArgs()`: AI arguments masked before reaching handler
683
+ 2. **MCP Middleware** — `maskToolResult()`: Handler result masked before returning to AI
684
+ 3. **Logger** — All log entries scanned for PII
685
+ 4. **Dashboard API** — All API responses masked
686
+
687
+ **Dashboard:** PrivacyPanel.tsx — PII masked/detected statistics, category distribution, Right to Erasure.
688
+
689
+ ---
690
+
691
+ ### 🐞 Detected Issues
692
+
693
+ | # | Issue | File | Fix |
694
+ |---|-------|------|-----|
695
+ | 1 | `MCP_TRANSPORT=stdio` env missing | `src/cli/commands/mcp.ts:66` | Added `MCP_TRANSPORT: "stdio"` |
696
+ | 2 | No success task learning | `src/modules/engines/evaluation-engine.ts` | `updateSpecialtyMemory()` should be called on success too |
697
+ | 3 | Specialty memory not auto-injected into AI | `silent-router.ts` / `discipline.ts` | `.atabey/memory/specialties/*.md` content should be injected on agent calls |
698
+ | 4 | No weekly cost summary | `finops.ts` | Add weekly rollup statistics to `atabey status` command |
699
+
700
+ ---
701
+
556
702
  ## Strategic Roadmap
557
703
 
558
704
  | # | Feature | Priority | Status |
559
705
  |---|---------|----------|--------|
560
- | 1 | Agent specialty memory → auto-sync to agent files | 🟠 High | Planned |
706
+ | 1 | Agent specialty memory → auto-sync to agent files | 🟠 High | 🟡 **Partial** (error learning only) |
561
707
  | 2 | MCP `prompts/` endpoint for session-level governance injection | 🟠 High | Planned |
562
708
  | 3 | Central Enterprise Server (telemetry ingest + org dashboard) | 🟡 Medium | Planned |
563
709
  | 4 | Dynamic rule loading from `.atabey/rules/*.json` | 🟡 Medium | Planned |
@@ -566,14 +712,17 @@ Full command list: see `atabey help` or [ARCHITECTURE.md](ARCHITECTURE.md)
566
712
 
567
713
  ## Security
568
714
 
715
+ ### Enterprise-Grade Governance
716
+ Atabey defines "enterprise-grade" through deterministic rules: AST compliance parsing, strict TypeScript type validation (zero `any`), syntax/linter checks, and automated unit tests, rather than unpredictable probabilistic algorithms.
717
+
569
718
  ### Zero Type Hole Policy
570
719
  - `any` type usage is **strictly forbidden**
571
720
  - All function inputs validated with Zod schemas
572
721
  - Type safety enforced in CI pipeline
573
722
 
574
- ### Zero Mock Policy
575
- - Mock data usage is **forbidden** (except 3rd party services)
576
- - Tests run against real implementations
723
+ ### Prudent Mocking Policy
724
+ - Core governance logic, schemas, and rule engines are verified against real implementations without mock data.
725
+ - Unit and integration boundaries (such as remote Hermes polling loops, network calls, and LLM provider interfaces) utilize lightweight, standard mocks to ensure isolation and fast test execution.
577
726
 
578
727
  ### PII Masking (KVKK Compliant)
579
728
  - All logs scanned for Personally Identifiable Information
package/bin/cli.js CHANGED
@@ -1,26 +1,93 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawn } from "node:child_process";
3
- import { fileURLToPath } from "node:url";
4
- import { dirname, join } from "node:path";
5
3
  import fs from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
6
 
7
7
  const __filename = fileURLToPath(import.meta.url);
8
8
  const __dirname = dirname(__filename);
9
9
 
10
+ // ─── Friendly Error Messages ──────────────────────────────────────
11
+ const ERRORS = {
12
+ BUILD_REQUIRED: `
13
+ ╔══════════════════════════════════════════════════════════╗
14
+ ║ 🚧 Atabey is not built yet ║
15
+ ╠══════════════════════════════════════════════════════════╣
16
+ ║ The compiled CLI was not found at: ║
17
+ ║ dist/src/cli/index.js ║
18
+ ║ ║
19
+ ║ 📋 To fix this, run: ║
20
+ ║ npm run build ║
21
+ ║ ║
22
+ ║ 💡 This compiles TypeScript source into JavaScript. ║
23
+ ║ After build completes, run atabey again. ║
24
+ ╚══════════════════════════════════════════════════════════╝
25
+ `,
26
+ NODE_VERSION: `
27
+ ╔══════════════════════════════════════════════════════════╗
28
+ ║ ⚠️ Unsupported Node.js version ║
29
+ ╠══════════════════════════════════════════════════════════╣
30
+ ║ Atabey requires Node.js >= 18.0.0 ║
31
+ ║ ║
32
+ ║ Current version: {version} ║
33
+ ║ ║
34
+ ║ 📋 To fix this: ║
35
+ ║ • Install Node.js 18+ via: ║
36
+ ║ nvm install 18 (if using nvm) ║
37
+ ║ brew install node (if using Homebrew) ║
38
+ ║ https://nodejs.org (official installer) ║
39
+ ║ ║
40
+ ║ • Then switch to it: ║
41
+ ║ nvm use 18 (if using nvm) ║
42
+ ╚══════════════════════════════════════════════════════════╝
43
+ `,
44
+ SPAWN_FAILED: `
45
+ ╔══════════════════════════════════════════════════════════╗
46
+ ║ ❌ Failed to start Atabey ║
47
+ ╠══════════════════════════════════════════════════════════╣
48
+ ║ Could not launch the CLI process. ║
49
+ ║ ║
50
+ ║ 📋 Common causes: ║
51
+ ║ • Out of memory ║
52
+ ║ • System resource limits ║
53
+ ║ • Permission issues ║
54
+ ║ ║
55
+ ║ Try running again, or check logs for details. ║
56
+ ╚══════════════════════════════════════════════════════════╝
57
+ `,
58
+ };
59
+
60
+ // ─── Node.js Version Check ────────────────────────────────────────
61
+ const nodeMajor = parseInt(process.versions.node.split(".")[0], 10);
62
+ if (nodeMajor < 18) {
63
+ process.stderr.write(ERRORS.NODE_VERSION.replace("{version}", process.versions.node));
64
+ process.exit(1);
65
+ }
66
+
67
+ // ─── Start CLI ────────────────────────────────────────────────────
10
68
  const cliPath = join(__dirname, "../dist/src/cli/index.js");
11
69
 
12
70
  if (!fs.existsSync(cliPath)) {
13
- process.stderr.write("\n[ERROR] Error: Compiled CLI not found at 'dist/src/cli/index.js'\n");
14
- process.stderr.write("[TIP] Solution Tip: Run 'npm run build' to compile the project first.\n\n");
71
+ process.stderr.write(ERRORS.BUILD_REQUIRED);
15
72
  process.exit(1);
16
73
  }
17
74
 
18
75
  const cmd = "node";
19
76
  const child = spawn(cmd, [cliPath, ...process.argv.slice(2)], {
20
77
  stdio: "inherit",
21
- shell: false
78
+ shell: false
79
+ });
80
+
81
+ child.on("error", (err) => {
82
+ process.stderr.write(ERRORS.SPAWN_FAILED);
83
+ process.stderr.write(`\n[DETAIL] ${err.message}\n\n`);
84
+ process.exit(1);
22
85
  });
23
86
 
24
87
  child.on("exit", (code) => {
88
+ if (code !== 0 && code !== null) {
89
+ // Non-zero exit — the CLI already printed the error
90
+ process.exit(code);
91
+ }
25
92
  process.exit(code ?? 0);
26
93
  });
@@ -16,6 +16,28 @@ import { RESOURCES, handleReadResource } from "./resources/index.js";
16
16
  import { TOOLS, toolHandlers, toolSchemas } from "./tools/index.js";
17
17
  // ─── Paths ────────────────────────────────────────────────────────
18
18
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
19
+ // ─── Friendly Startup Validation ──────────────────────────────────
20
+ function validateEnvironment() {
21
+ // Node.js version check
22
+ const nodeMajor = parseInt(process.versions.node.split(".")[0], 10);
23
+ if (nodeMajor < 18) {
24
+ process.stderr.write(`
25
+ ╔══════════════════════════════════════════════════════════╗
26
+ ║ ⚠️ Unsupported Node.js version ║
27
+ ╠══════════════════════════════════════════════════════════╣
28
+ ║ Atabey MCP requires Node.js >= 18.0.0 ║
29
+ ║ ║
30
+ ║ Current version: ${process.versions.node} ║
31
+ ║ ║
32
+ ║ 📋 To fix this: ║
33
+ ║ nvm install 18 && nvm use 18 (if using nvm) ║
34
+ ║ brew install node (if using Homebrew) ║
35
+ ║ https://nodejs.org (official installer) ║
36
+ ╚══════════════════════════════════════════════════════════╝
37
+ `);
38
+ process.exit(1);
39
+ }
40
+ }
19
41
  function findPackageJson(startDir) {
20
42
  let currentDir = startDir;
21
43
  while (currentDir !== path.parse(currentDir).root) {
@@ -24,16 +46,68 @@ function findPackageJson(startDir) {
24
46
  return pkgPath;
25
47
  currentDir = path.dirname(currentDir);
26
48
  }
27
- throw new Error("Could not find package.json for atabey-mcp");
49
+ process.stderr.write(`
50
+ ╔══════════════════════════════════════════════════════════╗
51
+ ║ 🚧 Package not found ║
52
+ ╠══════════════════════════════════════════════════════════╣
53
+ ║ Atabey MCP package.json could not be located. ║
54
+ ║ ║
55
+ ║ This usually means: ║
56
+ ║ 1. The package was not installed correctly ║
57
+ ║ 2. Node modules are missing ║
58
+ ║ ║
59
+ ║ 📋 To fix this: ║
60
+ ║ npm install -g atabey (global install) ║
61
+ ║ npm install (local install) ║
62
+ ║ npm run build (if developing) ║
63
+ ╚══════════════════════════════════════════════════════════╝
64
+ `);
65
+ process.exit(1);
28
66
  }
67
+ validateEnvironment();
29
68
  const pkgPath = findPackageJson(__dirname);
30
69
  const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
31
70
  const serverVersion = pkg.version;
71
+ // Validate environment variables with friendly messages
32
72
  const PROJECT_ROOT = process.env.ATABEY_PROJECT_ROOT || process.cwd();
73
+ if (!process.env.ATABEY_PROJECT_ROOT) {
74
+ const transportMode = process.env.MCP_TRANSPORT || "unified";
75
+ if (transportMode !== "stdio") {
76
+ process.stderr.write(`
77
+ ╔══════════════════════════════════════════════════════════╗
78
+ ║ 💡 Tip: Set ATABEY_PROJECT_ROOT ║
79
+ ╠══════════════════════════════════════════════════════════╣
80
+ ║ In HTTP/SSE mode, it's recommended to explicitly set ║
81
+ ║ the project root to avoid confusion. ║
82
+ ║ ║
83
+ ║ Example: ║
84
+ ║ export ATABEY_PROJECT_ROOT=/path/to/your/project ║
85
+ ║ ║
86
+ ║ Using current directory: ${process.cwd()} ║
87
+ ╚══════════════════════════════════════════════════════════╝
88
+ `);
89
+ }
90
+ }
33
91
  const FRAMEWORK_DIR = process.env.ATABEY_FRAMEWORK_DIR || path.join(PROJECT_ROOT, ".atabey");
34
- const UI_DIST_PATH = path.join(__dirname, "../../dist/dashboard");
92
+ const UI_DIST_PATH = path.join(__dirname, "../../dashboard/dist");
35
93
  // ─── Ports ────────────────────────────────────────────────────────
36
94
  const PORT = parseInt(process.env.MCP_PORT || "5858", 10);
95
+ if (isNaN(PORT) || PORT < 1 || PORT > 65535) {
96
+ process.stderr.write(`
97
+ ╔══════════════════════════════════════════════════════════╗
98
+ ║ ❌ Invalid MCP_PORT ║
99
+ ╠══════════════════════════════════════════════════════════╣
100
+ ║ The port must be a number between 1 and 65535. ║
101
+ ║ ║
102
+ ║ You set: MCP_PORT=${process.env.MCP_PORT || "(empty)"} ║
103
+ ║ ║
104
+ ║ 📋 To fix this: ║
105
+ ║ export MCP_PORT=5858 (default) ║
106
+ ║ export MCP_PORT=8080 (alternative) ║
107
+ ╚══════════════════════════════════════════════════════════╝
108
+ `);
109
+ process.exit(1);
110
+ }
37
111
  const HOST = process.env.MCP_HOST || "0.0.0.0";
38
112
  // ─── MCP Server ───────────────────────────────────────────────────
39
113
  const server = new Server({ name: "atabey-mcp", version: serverVersion }, { capabilities: { tools: {}, resources: {} } });
@@ -242,7 +316,6 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
242
316
  // [AUTO-ROLLBACK] Check write results for governance violations
243
317
  if (name === "write_file" || name === "replace_text" || name === "patch_file") {
244
318
  try {
245
- const responseText = result.content?.filter(b => b.type === "text").map(b => b.text).join(" ") || "";
246
319
  const filePath = maskedArgs.path || "";
247
320
  const content = maskedArgs.content || "";
248
321
  if (filePath && content) {