stealthos-cli 0.1.0-alpha.2 → 0.1.0-alpha.4

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 (178) hide show
  1. package/ai/CONTRACT.md +110 -0
  2. package/ai/INDEX.md +203 -0
  3. package/ai/README.md +434 -0
  4. package/ai/ROUTER.md +288 -0
  5. package/ai/agents/README.md +103 -0
  6. package/ai/agents/architect.md +59 -0
  7. package/ai/agents/backend-engineer.md +62 -0
  8. package/ai/agents/founder.md +45 -0
  9. package/ai/agents/frontend-engineer.md +61 -0
  10. package/ai/agents/product-manager.md +56 -0
  11. package/ai/agents/qa-engineer.md +53 -0
  12. package/ai/agents/researcher.md +74 -0
  13. package/ai/agents/reviewer.md +73 -0
  14. package/ai/agents/security-engineer.md +59 -0
  15. package/ai/agents/sre-engineer.md +70 -0
  16. package/ai/agents/tech-lead.md +70 -0
  17. package/ai/architecture/README.md +35 -0
  18. package/ai/architecture/components.md +24 -0
  19. package/ai/architecture/containers.md +30 -0
  20. package/ai/architecture/event-flows.md +36 -0
  21. package/ai/architecture/sequence-diagrams.md +38 -0
  22. package/ai/architecture/system-context.md +46 -0
  23. package/ai/architecture/threat-modeling.md +40 -0
  24. package/ai/blueprints/README.md +67 -0
  25. package/ai/blueprints/_schema.json +40 -0
  26. package/ai/blueprints/ai-platform.json +28 -0
  27. package/ai/blueprints/crm.json +22 -0
  28. package/ai/blueprints/game.json +25 -0
  29. package/ai/blueprints/mobile.json +24 -0
  30. package/ai/blueprints/realtime.json +22 -0
  31. package/ai/blueprints/saas.json +25 -0
  32. package/ai/blueprints/telemetry.json +30 -0
  33. package/ai/blueprints/web.json +23 -0
  34. package/ai/bootstrap/discovery-questions.md +117 -0
  35. package/ai/bootstrap/dispatcher.md +85 -0
  36. package/ai/bootstrap/existing-project.md +191 -0
  37. package/ai/bootstrap/new-project.md +127 -0
  38. package/ai/bootstrap/tech-mapping.md +164 -0
  39. package/ai/clients/README.md +114 -0
  40. package/ai/clients/antigravity.md +125 -0
  41. package/ai/clients/claude-code.md +65 -0
  42. package/ai/clients/cline.md +69 -0
  43. package/ai/clients/codex-aider-cli.md +82 -0
  44. package/ai/clients/continue.md +67 -0
  45. package/ai/clients/copilot.md +49 -0
  46. package/ai/clients/cursor.md +81 -0
  47. package/ai/clients/snippets/mcp-absolute-paths.json +9 -0
  48. package/ai/clients/snippets/mcp-http.json +7 -0
  49. package/ai/clients/snippets/mcp-stdio.json +9 -0
  50. package/ai/clients/trae.md +69 -0
  51. package/ai/clients/windsurf.md +71 -0
  52. package/ai/core/pipeline/execution-engine.md +157 -0
  53. package/ai/engineering/README.md +32 -0
  54. package/ai/engineering/observability/incident-response.md +82 -0
  55. package/ai/evals/protocol-tests.md +150 -0
  56. package/ai/evolution/agent-evolution.md +161 -0
  57. package/ai/evolution/improvements.md +91 -0
  58. package/ai/evolution/learnings.md +49 -0
  59. package/ai/evolution/patterns-discovered.md +48 -0
  60. package/ai/execution/README.md +33 -0
  61. package/ai/execution/backlog.md +27 -0
  62. package/ai/execution/milestones.md +26 -0
  63. package/ai/execution/roadmap.md +30 -0
  64. package/ai/execution/sprint.md +42 -0
  65. package/ai/governance/README.md +34 -0
  66. package/ai/governance/architecture-principles.md +99 -0
  67. package/ai/governance/definition-of-done.md +88 -0
  68. package/ai/governance/definition-of-ready.md +69 -0
  69. package/ai/governance/engineering-principles.md +70 -0
  70. package/ai/governance/quality-gates.md +85 -0
  71. package/ai/governance/security-policies.md +84 -0
  72. package/ai/hooks/enforce-audit.ps1 +41 -0
  73. package/ai/hooks/enforce-audit.sh +39 -0
  74. package/ai/hooks/guard-edit.ps1 +182 -0
  75. package/ai/hooks/guard-edit.sh +161 -0
  76. package/ai/hooks/inject-os-reminder.ps1 +40 -0
  77. package/ai/hooks/inject-os-reminder.sh +16 -0
  78. package/ai/manifest.json +238 -0
  79. package/ai/memory/_detected-stack.json +33 -0
  80. package/ai/memory/_summary.md +49 -0
  81. package/ai/memory/archive/.gitkeep +3 -0
  82. package/ai/memory/completed-tasks.md +156 -0
  83. package/ai/memory/decisions.md +257 -0
  84. package/ai/memory/errors-and-solutions.md +41 -0
  85. package/ai/memory/known-issues.md +40 -0
  86. package/ai/memory/pending-tasks.md +37 -0
  87. package/ai/memory/project-context.md +67 -0
  88. package/ai/operating-system/architecture.md +54 -0
  89. package/ai/operating-system/coding-standards.md +84 -0
  90. package/ai/operating-system/folder-structure.md +126 -0
  91. package/ai/operating-system/performance-rules.md +86 -0
  92. package/ai/operating-system/quality-control.md +81 -0
  93. package/ai/operating-system/security-rules.md +91 -0
  94. package/ai/operating-system/workflow.md +86 -0
  95. package/ai/product/README.md +24 -0
  96. package/ai/product/business-rules.md +26 -0
  97. package/ai/product/personas.md +29 -0
  98. package/ai/product/user-journeys.md +30 -0
  99. package/ai/product/vision.md +35 -0
  100. package/ai/rules/behavior.md +45 -0
  101. package/ai/rules/do.md +47 -0
  102. package/ai/rules/dont.md +46 -0
  103. package/ai/rules/execution-flow.md +125 -0
  104. package/ai/rules/structural-constraints.md +59 -0
  105. package/ai/rules/structure-canon.md +116 -0
  106. package/ai/runtime.md +179 -0
  107. package/ai/scripts/detect-stack.ps1 +166 -0
  108. package/ai/scripts/detect-stack.sh +172 -0
  109. package/ai/scripts/init-ai-os.ps1 +170 -0
  110. package/ai/scripts/init-ai-os.sh +99 -0
  111. package/ai/scripts/lint-os.ps1 +99 -0
  112. package/ai/scripts/lint-os.sh +85 -0
  113. package/ai/scripts/start-os.ps1 +151 -0
  114. package/ai/scripts/start-os.sh +141 -0
  115. package/ai/server/README.md +105 -0
  116. package/ai/server/aios-server.mjs +2134 -0
  117. package/ai/server/package-lock.json +802 -0
  118. package/ai/server/package.json +31 -0
  119. package/ai/server/src/analyzer/graph-builder.ts +92 -0
  120. package/ai/server/src/analyzer/index.ts +191 -0
  121. package/ai/server/src/analyzer/module-mapper.ts +171 -0
  122. package/ai/server/src/analyzer/smell-detector.ts +54 -0
  123. package/ai/server/src/analyzer/stack-detector.ts +70 -0
  124. package/ai/server/src/index.ts +16 -0
  125. package/ai/server/src/packager/context-builder.ts +217 -0
  126. package/ai/server/src/packager/index.ts +3 -0
  127. package/ai/server/src/packager/memory-injector.ts +128 -0
  128. package/ai/server/src/packager/module-summarizer.ts +60 -0
  129. package/ai/server/src/packager/token-estimator.ts +26 -0
  130. package/ai/server/src/snapshot/index.ts +3 -0
  131. package/ai/server/src/snapshot/snapshot-creator.ts +206 -0
  132. package/ai/server/src/snapshot/snapshot-diff.ts +86 -0
  133. package/ai/server/src/snapshot/snapshot-restore.ts +14 -0
  134. package/ai/server/src/types.ts +94 -0
  135. package/ai/server/tsconfig.json +26 -0
  136. package/ai/skills/architecture-design.md +82 -0
  137. package/ai/skills/backend-engineering.md +57 -0
  138. package/ai/skills/database-design.md +76 -0
  139. package/ai/skills/frontend-engineering.md +63 -0
  140. package/ai/skills/performance.md +73 -0
  141. package/ai/skills/scalability.md +84 -0
  142. package/ai/skills/security.md +71 -0
  143. package/ai/skills/testing.md +77 -0
  144. package/ai/specs/ADR/ADR-0002-typescript-runtime.md +103 -0
  145. package/ai/specs/ADR/ADR-0004-runtime-orchestrator.md +94 -0
  146. package/ai/specs/ADR/ADR-0005-workflow-engine.md +105 -0
  147. package/ai/specs/ADR/ADR-0006-runtime-state.md +104 -0
  148. package/ai/specs/ADR/ADR-0007-state-compiler-drift-context-layers-artifact-index.md +82 -0
  149. package/ai/specs/ADR/ADR-0008-intent-runtime-discovery-branching.md +93 -0
  150. package/ai/specs/ADR/ADR-0009-confidence-system-maturity-tracking.md +113 -0
  151. package/ai/specs/ADR/ADR-0010-structural-architecture-standards.md +121 -0
  152. package/ai/specs/ADR/ADR-0011-mcp-prompts.md +86 -0
  153. package/ai/specs/ADR/ADR-0012-stealthos-hybrid-architecture.md +174 -0
  154. package/ai/specs/ADR/_TEMPLATE.md +60 -0
  155. package/ai/specs/BRD/_TEMPLATE.md +50 -0
  156. package/ai/specs/PRD/_TEMPLATE.md +72 -0
  157. package/ai/specs/README.md +43 -0
  158. package/ai/specs/RFC/RFC-0001-runtime-orchestrator.md +149 -0
  159. package/ai/specs/RFC/RFC-0002-runtime-orchestrator-extended.md +134 -0
  160. package/ai/specs/RFC/_TEMPLATE.md +61 -0
  161. package/ai/specs/RUNBOOKS/_TEMPLATE.md +68 -0
  162. package/ai/specs/SDD/_TEMPLATE.md +104 -0
  163. package/ai/specs/TASKS/_TEMPLATE.md +52 -0
  164. package/ai/tools/debugging.md +64 -0
  165. package/ai/tools/dependency-analysis.md +46 -0
  166. package/ai/tools/internet-research.md +42 -0
  167. package/ai/tools/mcp-discovery.md +44 -0
  168. package/ai/workflows/_schema.json +81 -0
  169. package/ai/workflows/init.json +148 -0
  170. package/ai/workflows/sync.json +71 -0
  171. package/ai/workflows/work.json +91 -0
  172. package/bin.cjs +7 -0
  173. package/package.json +9 -3
  174. package/scripts/bundle-ai.mjs +58 -0
  175. package/src/cli.mjs +1 -1
  176. package/src/commands/install.mjs +35 -11
  177. package/src/lib/resolve-source.mjs +27 -10
  178. package/stealthos +0 -2
@@ -0,0 +1,99 @@
1
+ # lint-os.ps1
2
+ # Valida integridade do AI Operating System:
3
+ # - Todos os arquivos do manifest existem
4
+ # - Links markdown internos resolvem
5
+ # - Frontmatter valido em arquivos .ai/
6
+
7
+ param(
8
+ [string]$TargetPath = (Get-Location).Path
9
+ )
10
+
11
+ $ErrorActionPreference = "Continue"
12
+ $errors = @()
13
+ $warnings = @()
14
+
15
+ function Add-Error($msg) { $script:errors += $msg; Write-Host "[ERR] $msg" -ForegroundColor Red }
16
+ function Add-Warn($msg) { $script:warnings += $msg; Write-Host "[WARN] $msg" -ForegroundColor Yellow }
17
+
18
+ # ----- Manifest check -----
19
+ $manifestPath = Join-Path $TargetPath ".ai\manifest.json"
20
+ if (-not (Test-Path $manifestPath)) {
21
+ Add-Error ".ai\manifest.json nao encontrado"
22
+ exit 1
23
+ }
24
+
25
+ $manifest = Get-Content $manifestPath -Raw | ConvertFrom-Json
26
+
27
+ foreach ($f in $manifest.required_files) {
28
+ $full = Join-Path $TargetPath ($f -replace '/', '\')
29
+ if (-not (Test-Path $full)) {
30
+ Add-Error "Arquivo obrigatorio ausente: $f"
31
+ }
32
+ }
33
+
34
+ # ----- Link check -----
35
+ $mdFiles = Get-ChildItem -Path (Join-Path $TargetPath ".ai") -Filter "*.md" -Recurse -ErrorAction SilentlyContinue |
36
+ Where-Object { $_.FullName -notmatch '\\node_modules\\' -and $_.FullName -notmatch '\\dist\\' }
37
+ $mdFiles += Get-ChildItem -Path $TargetPath -Filter "CLAUDE.md" -ErrorAction SilentlyContinue
38
+ $mdFiles += Get-ChildItem -Path $TargetPath -Filter "GEMINI.md" -ErrorAction SilentlyContinue
39
+ $mdFiles += Get-ChildItem -Path $TargetPath -Filter "GPT.md" -ErrorAction SilentlyContinue
40
+
41
+ foreach ($file in $mdFiles) {
42
+ $content = Get-Content $file.FullName -Raw
43
+ $relFile = $file.FullName.Substring($TargetPath.Length + 1)
44
+
45
+ # Matches [texto](path) onde path comeca com . ou /
46
+ $matches = [regex]::Matches($content, '\[([^\]]+)\]\((\.{1,2}[^\)\s#]+)(?:#[^\)]*)?\)')
47
+ foreach ($m in $matches) {
48
+ $link = $m.Groups[2].Value
49
+ # Resolve relative to file dir
50
+ $resolved = Join-Path $file.DirectoryName $link
51
+ try {
52
+ $abs = [System.IO.Path]::GetFullPath($resolved)
53
+ if (-not (Test-Path $abs)) {
54
+ Add-Warn "${relFile}: link quebrado -> $link"
55
+ }
56
+ } catch {
57
+ Add-Warn "${relFile}: link nao resolvivel -> $link"
58
+ }
59
+ }
60
+ }
61
+
62
+ # ----- Frontmatter check -----
63
+ $aiMdFiles = Get-ChildItem -Path (Join-Path $TargetPath ".ai") -Filter "*.md" -Recurse -ErrorAction SilentlyContinue |
64
+ Where-Object { $_.FullName -notmatch '\\node_modules\\' -and $_.FullName -notmatch '\\dist\\' }
65
+ foreach ($file in $aiMdFiles) {
66
+ $content = Get-Content $file.FullName -Raw
67
+ $relFile = $file.FullName.Substring($TargetPath.Length + 1)
68
+
69
+ # Pular arquivos de log/append (memory/*, evolution/*) — frontmatter eh opcional
70
+ if ($relFile -match '\\memory\\(?!project-context)' -or $relFile -match '\\evolution\\') { continue }
71
+ # Pular .ai/server/README.md (codigo, nao doc do OS)
72
+ if ($relFile -match '\\server\\') { continue }
73
+ # Pular specs templates (estrutura de template, nao OS docs)
74
+ if ($relFile -match '\\specs\\' -and $relFile -match '_TEMPLATE\.md$') { continue }
75
+
76
+ # Verifica se arquivo comeca com bloco de frontmatter YAML (--- ... ---)
77
+ if ($content -notmatch '(?s)^\s*---\s*\r?\n.*?\r?\n---\s*\r?\n') {
78
+ Add-Warn "${relFile}: sem frontmatter (version/tier/tokens)"
79
+ }
80
+ }
81
+
82
+ # ----- Runtime v0.1 build check (warn-only) -----
83
+ $capabilities = $manifest.capabilities
84
+ if ($capabilities -and $capabilities.runtime_v0_1) {
85
+ $distPath = Join-Path $TargetPath ".ai\server\dist\index.mjs"
86
+ if (-not (Test-Path $distPath)) {
87
+ Add-Warn "Runtime v0.1 declarado no manifest mas dist/index.mjs ausente. Rode: cd .ai\server; npm install; npm run build"
88
+ } else {
89
+ Write-Host "[OK] Runtime v0.1 dist presente: .ai\server\dist\index.mjs" -ForegroundColor Green
90
+ }
91
+ }
92
+
93
+ # ----- Resumo -----
94
+ Write-Host ""
95
+ Write-Host "===== Lint Summary =====" -ForegroundColor Cyan
96
+ Write-Host "Errors: $($errors.Count)"
97
+ Write-Host "Warnings: $($warnings.Count)"
98
+
99
+ if ($errors.Count -gt 0) { exit 1 } else { exit 0 }
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env bash
2
+ # lint-os.sh - Valida integridade do AI OS (Unix)
3
+ set -euo pipefail
4
+
5
+ TARGET="$(pwd)"
6
+ while [[ $# -gt 0 ]]; do
7
+ case "$1" in
8
+ --target) TARGET="$2"; shift 2 ;;
9
+ *) shift ;;
10
+ esac
11
+ done
12
+
13
+ errors=0
14
+ warnings=0
15
+ add_err() { echo -e "\033[0;31m[ERR]\033[0m $1"; errors=$((errors+1)); }
16
+ add_warn() { echo -e "\033[0;33m[WARN]\033[0m $1"; warnings=$((warnings+1)); }
17
+
18
+ MANIFEST="$TARGET/.ai/manifest.json"
19
+ [[ -f "$MANIFEST" ]] || { add_err ".ai/manifest.json ausente"; exit 1; }
20
+
21
+ # required_files (precisa jq OU node OU python3)
22
+ if command -v jq &>/dev/null; then
23
+ REQ_FILES=$(jq -r '.required_files[]' "$MANIFEST")
24
+ elif command -v python3 &>/dev/null; then
25
+ REQ_FILES=$(python3 -c "import json,sys; print('\n'.join(json.load(open('$MANIFEST'))['required_files']))")
26
+ elif command -v node &>/dev/null; then
27
+ REQ_FILES=$(node -e "console.log(JSON.parse(require('fs').readFileSync('$MANIFEST','utf8')).required_files.join('\n'))")
28
+ else
29
+ add_warn "Sem jq/python3/node — pulando validacao de manifest"
30
+ REQ_FILES=""
31
+ fi
32
+
33
+ while IFS= read -r f; do
34
+ [[ -z "$f" ]] && continue
35
+ [[ -e "$TARGET/$f" ]] || add_err "Arquivo obrigatorio ausente: $f"
36
+ done <<< "$REQ_FILES"
37
+
38
+ # Frontmatter check em .ai/**.md (ignora memory/archive, evolution/, e arquivos especificos)
39
+ while IFS= read -r mdfile; do
40
+ rel="${mdfile#$TARGET/}"
41
+ # Pular node_modules, dist, e specs templates
42
+ [[ "$rel" =~ /node_modules/ ]] && continue
43
+ [[ "$rel" =~ /dist/ ]] && continue
44
+ [[ "$rel" =~ \.ai/server/ ]] && continue
45
+ [[ "$rel" =~ /specs/.*_TEMPLATE\.md$ ]] && continue
46
+ # Pular memory/* (exceto project-context.md) e evolution/*
47
+ [[ "$rel" =~ \.ai/memory/(.*\.md)$ && ! "$rel" =~ project-context\.md$ ]] && continue
48
+ [[ "$rel" =~ \.ai/evolution/ ]] && continue
49
+ [[ "$rel" =~ \.ai/memory/archive/ ]] && continue
50
+ # Verificar frontmatter YAML --- ... ---
51
+ head -1 "$mdfile" | grep -q '^---' || add_warn "$rel: sem frontmatter"
52
+ done < <(find "$TARGET/.ai" -name "*.md" -type f 2>/dev/null | grep -v node_modules | grep -v '/dist/')
53
+
54
+ # Link check basico — procura links [texto](./...) e verifica existencia
55
+ while IFS= read -r mdfile; do
56
+ rel="${mdfile#$TARGET/}"
57
+ [[ "$rel" =~ /node_modules/ ]] && continue
58
+ [[ "$rel" =~ /dist/ ]] && continue
59
+ file_dir="$(dirname "$mdfile")"
60
+ grep -oE '\]\(\.{1,2}[^)#[:space:]]+(\#[^)]*)?\)' "$mdfile" 2>/dev/null | \
61
+ sed -E 's/\]\((.+)\)/\1/; s/#.*$//' | \
62
+ while IFS= read -r link; do
63
+ [[ -z "$link" ]] && continue
64
+ resolved="$(cd "$file_dir" && cd "$(dirname "$link")" 2>/dev/null && pwd)/$(basename "$link")"
65
+ [[ -e "$resolved" ]] || add_warn "$rel: link quebrado -> $link"
66
+ done
67
+ done < <(find "$TARGET/.ai" "$TARGET" -maxdepth 2 -name "*.md" -type f 2>/dev/null | grep -v node_modules | grep -v '/dist/')
68
+
69
+ # Runtime v0.1 build check (warn-only)
70
+ if command -v jq &>/dev/null; then
71
+ has_runtime=$(jq -r '.capabilities.runtime_v0_1 // false' "$MANIFEST" 2>/dev/null)
72
+ if [[ "$has_runtime" == "true" ]]; then
73
+ if [[ ! -f "$TARGET/.ai/server/dist/index.mjs" ]]; then
74
+ add_warn "Runtime v0.1 declarado no manifest mas dist/index.mjs ausente. Rode: cd .ai/server && npm install && npm run build"
75
+ else
76
+ echo -e "\033[0;32m[OK]\033[0m Runtime v0.1 dist presente: .ai/server/dist/index.mjs"
77
+ fi
78
+ fi
79
+ fi
80
+
81
+ echo ""
82
+ echo "===== Lint Summary ====="
83
+ echo "Errors: $errors"
84
+ echo "Warnings: $warnings"
85
+ [[ $errors -gt 0 ]] && exit 1 || exit 0
@@ -0,0 +1,151 @@
1
+ # start-os.ps1 — Inicia o daemon AI OS (Windows)
2
+ # Uso:
3
+ # .\scripts\start-os.ps1 # MCP stdio (foreground)
4
+ # .\scripts\start-os.ps1 -Http # HTTP em background, porta 47781 (auto-fallback)
5
+ # .\scripts\start-os.ps1 -Http -Port 8080
6
+ # .\scripts\start-os.ps1 -Status # checa se daemon esta rodando
7
+ # .\scripts\start-os.ps1 -Stop
8
+
9
+ param(
10
+ [switch]$Http,
11
+ [int]$Port = 47781,
12
+ [switch]$Status,
13
+ [switch]$Stop,
14
+ [switch]$Build,
15
+ [switch]$NoRuntime,
16
+ [string]$ProjectRoot = (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent)
17
+ )
18
+
19
+ $ErrorActionPreference = "Stop"
20
+ $serverPath = Join-Path $ProjectRoot ".ai\server\aios-server.mjs"
21
+ $serverDir = Join-Path $ProjectRoot ".ai\server"
22
+ $distPath = Join-Path $serverDir "dist\index.mjs"
23
+ $nodeModulesPath = Join-Path $serverDir "node_modules"
24
+ $runtimeDir = Join-Path $ProjectRoot ".ai\.runtime"
25
+ $pidFile = Join-Path $runtimeDir "daemon.pid"
26
+ $portFile = Join-Path $runtimeDir "port"
27
+ $logFile = Join-Path $runtimeDir "daemon.log"
28
+
29
+ function Write-Ok($m) { Write-Host "[OK] $m" -ForegroundColor Green }
30
+ function Write-Info($m) { Write-Host "[..] $m" -ForegroundColor Cyan }
31
+ function Write-Warn($m) { Write-Host "[WARN] $m" -ForegroundColor Yellow }
32
+ function Write-Err($m) { Write-Host "[ERR] $m" -ForegroundColor Red }
33
+
34
+ # Verifica Node
35
+ if (-not (Get-Command node -ErrorAction SilentlyContinue)) {
36
+ Write-Err "Node.js nao encontrado. Instale Node >= 18 e tente novamente."
37
+ exit 1
38
+ }
39
+
40
+ if (-not (Test-Path $serverPath)) {
41
+ Write-Err "Servidor nao encontrado em: $serverPath"
42
+ exit 1
43
+ }
44
+
45
+ # Runtime v0.1: verificar dist/index.mjs
46
+ if (-not $NoRuntime -and -not ($Status -or $Stop)) {
47
+ $distExists = Test-Path $distPath
48
+ if (-not $distExists -and $Build) {
49
+ if (-not (Get-Command npm -ErrorAction SilentlyContinue)) {
50
+ Write-Err "npm nao encontrado mas -Build foi solicitado. Instale Node >= 18 (npm vem junto)."
51
+ exit 1
52
+ }
53
+ Write-Info "Runtime v0.1 nao compilado. Rodando npm install + npm run build em $serverDir..."
54
+ Push-Location $serverDir
55
+ try {
56
+ if (-not (Test-Path $nodeModulesPath)) {
57
+ & npm install
58
+ if ($LASTEXITCODE -ne 0) { Write-Err "npm install falhou (exit $LASTEXITCODE)"; Pop-Location; exit 1 }
59
+ }
60
+ & npm run build
61
+ if ($LASTEXITCODE -ne 0) { Write-Err "npm run build falhou (exit $LASTEXITCODE)"; Pop-Location; exit 1 }
62
+ Write-Ok "Runtime v0.1 compilado em $distPath"
63
+ } finally {
64
+ Pop-Location
65
+ }
66
+ } elseif (-not $distExists) {
67
+ Write-Warn "Runtime v0.1 nao compilado (dist/index.mjs ausente). Daemon iniciara com 12 tools base apenas."
68
+ Write-Warn "Para habilitar as 5 tools v0.1 (analyze_project/build_context_package/snapshot*):"
69
+ Write-Warn " cd .ai\server; npm install; npm run build"
70
+ Write-Warn "Ou rode este script com -Build para compilar automaticamente."
71
+ }
72
+ }
73
+
74
+ # ---- STATUS ----
75
+ if ($Status) {
76
+ if (Test-Path $pidFile) {
77
+ $existingPid = Get-Content $pidFile -ErrorAction SilentlyContinue
78
+ $running = Get-Process -Id $existingPid -ErrorAction SilentlyContinue
79
+ if ($running) {
80
+ $port = if (Test-Path $portFile) { Get-Content $portFile } else { "n/a" }
81
+ Write-Ok "Daemon ativo: PID $existingPid, porta $port"
82
+ exit 0
83
+ } else {
84
+ Write-Info "Daemon inativo (PID file antigo)"
85
+ Remove-Item $pidFile -Force -ErrorAction SilentlyContinue
86
+ exit 1
87
+ }
88
+ } else {
89
+ Write-Info "Daemon inativo"
90
+ exit 1
91
+ }
92
+ }
93
+
94
+ # ---- STOP ----
95
+ if ($Stop) {
96
+ if (Test-Path $pidFile) {
97
+ $existingPid = Get-Content $pidFile
98
+ $proc = Get-Process -Id $existingPid -ErrorAction SilentlyContinue
99
+ if ($proc) {
100
+ Stop-Process -Id $existingPid -Force
101
+ Write-Ok "Daemon parado (PID $existingPid)"
102
+ } else {
103
+ Write-Info "Processo $existingPid ja nao existe"
104
+ }
105
+ Remove-Item $pidFile -Force -ErrorAction SilentlyContinue
106
+ Remove-Item $portFile -Force -ErrorAction SilentlyContinue
107
+ } else {
108
+ Write-Info "Nenhum daemon registrado"
109
+ }
110
+ exit 0
111
+ }
112
+
113
+ # ---- START ----
114
+ New-Item -ItemType Directory -Force -Path $runtimeDir | Out-Null
115
+
116
+ # Checa se ja existe um rodando
117
+ if (Test-Path $pidFile) {
118
+ $existingPid = Get-Content $pidFile
119
+ if (Get-Process -Id $existingPid -ErrorAction SilentlyContinue) {
120
+ Write-Info "Daemon ja rodando (PID $existingPid). Use -Stop para parar primeiro."
121
+ exit 0
122
+ } else {
123
+ Remove-Item $pidFile -Force
124
+ }
125
+ }
126
+
127
+ if ($Http) {
128
+ Write-Info "Iniciando daemon AI OS em modo HTTP (porta inicial: $Port)..."
129
+ # Quotar args com espaco para Start-Process -ArgumentList
130
+ $procArgs = @("`"$serverPath`"", "--http", "--port", "$Port")
131
+ $proc = Start-Process -FilePath "node" -ArgumentList $procArgs -WorkingDirectory $ProjectRoot `
132
+ -RedirectStandardOutput $logFile -RedirectStandardError "$logFile.err" `
133
+ -WindowStyle Hidden -PassThru
134
+ $proc.Id | Out-File -FilePath $pidFile -Encoding ascii
135
+ Start-Sleep -Seconds 2
136
+ if (Test-Path $portFile) {
137
+ $actualPort = Get-Content $portFile
138
+ Write-Ok "Daemon ativo: PID $($proc.Id), HTTP em http://127.0.0.1:$actualPort"
139
+ Write-Host " Health: http://127.0.0.1:$actualPort/health"
140
+ Write-Host " Tools: http://127.0.0.1:$actualPort/tools"
141
+ Write-Host " Logs: $logFile"
142
+ } else {
143
+ Write-Info "Daemon iniciado (PID $($proc.Id)). Aguarde alguns segundos e cheque logs em $logFile"
144
+ }
145
+ } else {
146
+ Write-Info "Iniciando daemon AI OS em modo MCP stdio (foreground)..."
147
+ Write-Info "Conecte seu cliente MCP usando: node `"$serverPath`""
148
+ Write-Info "Para rodar em background HTTP, use: -Http"
149
+ Write-Host ""
150
+ & node "$serverPath"
151
+ }
@@ -0,0 +1,141 @@
1
+ #!/usr/bin/env bash
2
+ # start-os.sh - Inicia o daemon AI OS (macOS/Linux)
3
+ # Uso:
4
+ # ./scripts/start-os.sh # MCP stdio (foreground)
5
+ # ./scripts/start-os.sh --http # HTTP em background, porta 47781
6
+ # ./scripts/start-os.sh --http --port 8080
7
+ # ./scripts/start-os.sh --status
8
+ # ./scripts/start-os.sh --stop
9
+
10
+ set -euo pipefail
11
+
12
+ MODE="stdio"
13
+ PORT=47781
14
+ ACTION="start"
15
+ DO_BUILD=0
16
+ NO_RUNTIME=0
17
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
18
+ PROJECT_ROOT="$(dirname "$(dirname "$SCRIPT_DIR")")"
19
+
20
+ while [[ $# -gt 0 ]]; do
21
+ case "$1" in
22
+ --http) MODE="http"; shift ;;
23
+ --port) PORT="$2"; shift 2 ;;
24
+ --status) ACTION="status"; shift ;;
25
+ --stop) ACTION="stop"; shift ;;
26
+ --build) DO_BUILD=1; shift ;;
27
+ --no-runtime) NO_RUNTIME=1; shift ;;
28
+ --project-root) PROJECT_ROOT="$2"; shift 2 ;;
29
+ *) echo "Arg desconhecido: $1" >&2; exit 1 ;;
30
+ esac
31
+ done
32
+
33
+ SERVER_PATH="$PROJECT_ROOT/.ai/server/aios-server.mjs"
34
+ SERVER_DIR="$PROJECT_ROOT/.ai/server"
35
+ DIST_PATH="$SERVER_DIR/dist/index.mjs"
36
+ RUNTIME_DIR="$PROJECT_ROOT/.ai/.runtime"
37
+ PID_FILE="$RUNTIME_DIR/daemon.pid"
38
+ PORT_FILE="$RUNTIME_DIR/port"
39
+ LOG_FILE="$RUNTIME_DIR/daemon.log"
40
+
41
+ c_g='\033[0;32m'; c_c='\033[0;36m'; c_r='\033[0;31m'; c_y='\033[0;33m'; c_n='\033[0m'
42
+ ok() { printf "${c_g}[OK]${c_n} %s\n" "$1"; }
43
+ info() { printf "${c_c}[..]${c_n} %s\n" "$1"; }
44
+ warn() { printf "${c_y}[WARN]${c_n} %s\n" "$1"; }
45
+ err() { printf "${c_r}[ERR]${c_n} %s\n" "$1" >&2; }
46
+
47
+ command -v node &>/dev/null || { err "Node.js nao encontrado (instale Node >= 18)"; exit 1; }
48
+ [[ -f "$SERVER_PATH" ]] || { err "Servidor nao encontrado: $SERVER_PATH"; exit 1; }
49
+
50
+ # Runtime v0.1: verificar dist/index.mjs
51
+ if [[ $NO_RUNTIME -eq 0 && "$ACTION" == "start" ]]; then
52
+ if [[ ! -f "$DIST_PATH" ]]; then
53
+ if [[ $DO_BUILD -eq 1 ]]; then
54
+ command -v npm &>/dev/null || { err "npm nao encontrado mas --build foi solicitado"; exit 1; }
55
+ info "Runtime v0.1 nao compilado. Rodando npm install + npm run build em $SERVER_DIR..."
56
+ (cd "$SERVER_DIR" && {
57
+ if [[ ! -d "node_modules" ]]; then npm install || { err "npm install falhou"; exit 1; } fi
58
+ npm run build || { err "npm run build falhou"; exit 1; }
59
+ })
60
+ ok "Runtime v0.1 compilado em $DIST_PATH"
61
+ else
62
+ warn "Runtime v0.1 nao compilado (dist/index.mjs ausente). Daemon iniciara com 12 tools base apenas."
63
+ warn "Para habilitar as 5 tools v0.1 (analyze_project/build_context_package/snapshot*):"
64
+ warn " cd .ai/server && npm install && npm run build"
65
+ warn "Ou rode este script com --build para compilar automaticamente."
66
+ fi
67
+ fi
68
+ fi
69
+
70
+ case "$ACTION" in
71
+ status)
72
+ if [[ -f "$PID_FILE" ]]; then
73
+ existing=$(cat "$PID_FILE")
74
+ if kill -0 "$existing" 2>/dev/null; then
75
+ port=$([[ -f "$PORT_FILE" ]] && cat "$PORT_FILE" || echo "n/a")
76
+ ok "Daemon ativo: PID $existing, porta $port"
77
+ exit 0
78
+ else
79
+ info "Daemon inativo (PID file antigo)"
80
+ rm -f "$PID_FILE"
81
+ exit 1
82
+ fi
83
+ else
84
+ info "Daemon inativo"
85
+ exit 1
86
+ fi
87
+ ;;
88
+
89
+ stop)
90
+ if [[ -f "$PID_FILE" ]]; then
91
+ existing=$(cat "$PID_FILE")
92
+ if kill -0 "$existing" 2>/dev/null; then
93
+ kill "$existing"
94
+ ok "Daemon parado (PID $existing)"
95
+ else
96
+ info "Processo $existing ja nao existe"
97
+ fi
98
+ rm -f "$PID_FILE" "$PORT_FILE"
99
+ else
100
+ info "Nenhum daemon registrado"
101
+ fi
102
+ exit 0
103
+ ;;
104
+
105
+ start)
106
+ mkdir -p "$RUNTIME_DIR"
107
+ if [[ -f "$PID_FILE" ]]; then
108
+ existing=$(cat "$PID_FILE")
109
+ if kill -0 "$existing" 2>/dev/null; then
110
+ info "Daemon ja rodando (PID $existing). Use --stop primeiro."
111
+ exit 0
112
+ fi
113
+ rm -f "$PID_FILE"
114
+ fi
115
+
116
+ if [[ "$MODE" == "http" ]]; then
117
+ info "Iniciando AI OS em modo HTTP (porta inicial: $PORT)..."
118
+ nohup node "$SERVER_PATH" --http --port "$PORT" \
119
+ >"$LOG_FILE" 2>"$LOG_FILE.err" &
120
+ new_pid=$!
121
+ echo "$new_pid" > "$PID_FILE"
122
+ disown
123
+ sleep 1
124
+ if [[ -f "$PORT_FILE" ]]; then
125
+ actual=$(cat "$PORT_FILE")
126
+ ok "Daemon ativo: PID $new_pid, HTTP em http://127.0.0.1:$actual"
127
+ echo " Health: http://127.0.0.1:$actual/health"
128
+ echo " Tools: http://127.0.0.1:$actual/tools"
129
+ echo " Logs: $LOG_FILE"
130
+ else
131
+ info "Daemon iniciado (PID $new_pid). Aguarde e cheque logs em $LOG_FILE"
132
+ fi
133
+ else
134
+ info "Iniciando AI OS em modo MCP stdio (foreground)..."
135
+ info "Conecte seu cliente MCP usando: node $SERVER_PATH"
136
+ info "Para rodar em background HTTP, use: --http"
137
+ echo ""
138
+ exec node "$SERVER_PATH"
139
+ fi
140
+ ;;
141
+ esac
@@ -0,0 +1,105 @@
1
+ # `.ai/server/` — MCP Daemon + Runtime v0.1
2
+
3
+ Este diretório contém **dois componentes**:
4
+
5
+ 1. **`aios-server.mjs`** — MCP daemon Node puro (zero deps em runtime). Implementa JSON-RPC 2.0 sobre stdio + HTTP opcional na porta 47781. Expõe **17 tools** (12 base + 5 do Runtime v0.1).
6
+ 2. **`src/` + `dist/`** — Runtime v0.1 em TypeScript (compilado para `dist/index.mjs` via `esbuild --bundle`). Implementa os três motores executáveis do AI-DOS v0.1.
7
+
8
+ ## Arquitetura
9
+
10
+ ```
11
+ aios-server.mjs (entry point .mjs, zero deps)
12
+
13
+ └─ import('dist/index.mjs') ← bundle único gerado pelo esbuild
14
+
15
+ ├─ analyzer/ ← Project State Engine
16
+ ├─ packager/ ← Context Packager
17
+ └─ snapshot/ ← Snapshot System
18
+ ```
19
+
20
+ O `aios-server.mjs` **continua funcionando sem `dist/`** (graceful degradation): só as 12 tools base ficam disponíveis. As 5 tools v0.1 retornam erro descritivo orientando o usuário a rodar o build.
21
+
22
+ ## Setup (primeira vez)
23
+
24
+ ```bash
25
+ cd .ai/server
26
+ npm install
27
+ npm run build
28
+ ```
29
+
30
+ Isso instala `ts-morph`, `commander`, e devDeps (`typescript`, `esbuild`, `@types/node`). Gera `dist/index.mjs` (bundle único, sem `node_modules` em runtime).
31
+
32
+ ## Comandos npm
33
+
34
+ | Comando | Ação |
35
+ |---|---|
36
+ | `npm run build` | Type-check + esbuild bundle → `dist/index.mjs`. Mantém `ts-morph` e `commander` como external (importados em runtime do `node_modules`). |
37
+ | `npm run build:standalone` | Bundle 100% self-contained (inclui `ts-morph` no bundle). Maior, mas remove dependência de `node_modules` em runtime. |
38
+ | `npm run dev` | `tsc --watch` (apenas type-check incremental). |
39
+ | `npm run typecheck` | `tsc --noEmit`. |
40
+ | `npm start` | Inicia o daemon stdio. |
41
+ | `npm run http` | Inicia o daemon em HTTP (porta 47781, auto-fallback). |
42
+
43
+ ## Estrutura `src/`
44
+
45
+ ```
46
+ src/
47
+ ├── types.ts # tipos compartilhados (ProjectState, ContextPackage, SnapshotManifest, ...)
48
+ ├── index.ts # API pública (re-exports)
49
+ ├── analyzer/
50
+ │ ├── index.ts # analyzeProject(root, options)
51
+ │ ├── stack-detector.ts # envelope dos scripts detect-stack.{ps1,sh}
52
+ │ ├── module-mapper.ts # ts-morph para TS/JS, regex fallback p/ outras
53
+ │ ├── graph-builder.ts # grafo de dependências + detecção de ciclos (DFS coloring)
54
+ │ └── smell-detector.ts # circular dep / large file / TODO / FIXME
55
+ ├── packager/
56
+ │ ├── index.ts # buildContextPackage(root, options)
57
+ │ ├── context-builder.ts # orquestrador
58
+ │ ├── module-summarizer.ts # ModuleInfo → YAML block
59
+ │ ├── memory-injector.ts # lê memory/decisions, errors, issues + ranking por keywords
60
+ │ └── token-estimator.ts # chars/3.8 heurística + headroom check (regra 40%)
61
+ └── snapshot/
62
+ ├── index.ts
63
+ ├── snapshot-creator.ts # captura state + SHA-256 hashes + memory snapshot
64
+ ├── snapshot-diff.ts # list + diff de snapshots
65
+ └── snapshot-restore.ts # stub v0.1 (throw); v0.2 implementa
66
+ ```
67
+
68
+ ## Tools expostas (MCP)
69
+
70
+ ### Base (sempre disponíveis)
71
+ - `aios_get_core_bundle`, `aios_route_query`, `aios_classify_task`
72
+ - `aios_read`, `aios_list`, `aios_search_memory`
73
+ - `aios_get_summary`, `aios_get_manifest`
74
+ - `aios_lint`, `aios_detect_stack`, `aios_validate_audit`, `aios_health`
75
+
76
+ ### Runtime v0.1 (requer `dist/`)
77
+ - `aios_analyze_project` — gera `.ai/context/project-state.{json,md}`
78
+ - `aios_build_context_package` — gera `.ai/context/packages/<slug>.{md,json}`
79
+ - `aios_snapshot` — gera `.ai/snapshots/<id>/`
80
+ - `aios_snapshot_list`
81
+ - `aios_snapshot_diff`
82
+
83
+ ## Slash commands relacionados
84
+
85
+ - `/analyze` → chama `aios_analyze_project`
86
+ - `/context --for "<intent>"` → chama `aios_build_context_package`
87
+ - `/snapshot <label>` → chama `aios_snapshot`
88
+
89
+ ## Decisões arquiteturais
90
+
91
+ - **ADR-0002** — adoção de TypeScript + `ts-morph` + `commander` + `esbuild`. Quebra "zero-deps" (apenas em dev). Justificativa em `.ai/specs/ADR/ADR-0002-typescript-runtime.md`.
92
+
93
+ ## Debug
94
+
95
+ - `dist/` não gerou: `npm run build` falha → ver erro do `tsc`; geralmente é uma referência quebrada em `src/`.
96
+ - Daemon não importa `dist/`: ver stderr do daemon — log `[aios] Runtime v0.1 dist failed to load: <razão>`.
97
+ - Tools v0.1 retornam erro mesmo após build: rodar `aios_health` e checar campo `runtime_v0_1` + `runtime_load_error`.
98
+
99
+ ## Próximos passos (v0.2 — fora deste sprint)
100
+
101
+ - `/dialog` e `/start` interativos
102
+ - Intent Analyzer + Spec Generator
103
+ - Embeddings + retrieval semântico
104
+ - Agentes executáveis
105
+ - Workflow engine (DAG)