deployready 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +136 -0
  3. package/bin/deployready.js +21 -0
  4. package/dist/agent/FileEditor.js +120 -0
  5. package/dist/agent/FileEditor.js.map +1 -0
  6. package/dist/agent/FixManager.js +47 -0
  7. package/dist/agent/FixManager.js.map +1 -0
  8. package/dist/agent/SessionManager.js +16 -0
  9. package/dist/agent/SessionManager.js.map +1 -0
  10. package/dist/agent/SystemPrompt.js +10 -0
  11. package/dist/agent/SystemPrompt.js.map +1 -0
  12. package/dist/agent/ToolDispatcher.js +14 -0
  13. package/dist/agent/ToolDispatcher.js.map +1 -0
  14. package/dist/ai/ClaudeHandler.js +73 -0
  15. package/dist/ai/ClaudeHandler.js.map +1 -0
  16. package/dist/ai/ContextChunker.js +29 -0
  17. package/dist/ai/ContextChunker.js.map +1 -0
  18. package/dist/ai/ModelRouter.js +86 -0
  19. package/dist/ai/ModelRouter.js.map +1 -0
  20. package/dist/ai/OllamaHandler.js +57 -0
  21. package/dist/ai/OllamaHandler.js.map +1 -0
  22. package/dist/ai/OpenAIHandler.js +51 -0
  23. package/dist/ai/OpenAIHandler.js.map +1 -0
  24. package/dist/ai/PromptBuilder.js +90 -0
  25. package/dist/ai/PromptBuilder.js.map +1 -0
  26. package/dist/ai/parseAiResponse.js +68 -0
  27. package/dist/ai/parseAiResponse.js.map +1 -0
  28. package/dist/ai/parseFix.js +29 -0
  29. package/dist/ai/parseFix.js.map +1 -0
  30. package/dist/analysis/IssueAggregator.js +37 -0
  31. package/dist/analysis/IssueAggregator.js.map +1 -0
  32. package/dist/analysis/ScoreCalculator.js +25 -0
  33. package/dist/analysis/ScoreCalculator.js.map +1 -0
  34. package/dist/analysis/SeverityScorer.js +17 -0
  35. package/dist/analysis/SeverityScorer.js.map +1 -0
  36. package/dist/analysis/VulnerabilityDetector.js +156 -0
  37. package/dist/analysis/VulnerabilityDetector.js.map +1 -0
  38. package/dist/analysis/rules.js +241 -0
  39. package/dist/analysis/rules.js.map +1 -0
  40. package/dist/cli/Commands.js +125 -0
  41. package/dist/cli/Commands.js.map +1 -0
  42. package/dist/cli/InteractiveShell.js +733 -0
  43. package/dist/cli/InteractiveShell.js.map +1 -0
  44. package/dist/cli/Onboarding.js +88 -0
  45. package/dist/cli/Onboarding.js.map +1 -0
  46. package/dist/config/ConfigManager.js +133 -0
  47. package/dist/config/ConfigManager.js.map +1 -0
  48. package/dist/core/CiGate.js +55 -0
  49. package/dist/core/CiGate.js.map +1 -0
  50. package/dist/core/Orchestrator.js +204 -0
  51. package/dist/core/Orchestrator.js.map +1 -0
  52. package/dist/core/Verifier.js +75 -0
  53. package/dist/core/Verifier.js.map +1 -0
  54. package/dist/dynamic/APIAnalyzer.js +66 -0
  55. package/dist/dynamic/APIAnalyzer.js.map +1 -0
  56. package/dist/dynamic/DynamicTester.js +36 -0
  57. package/dist/dynamic/DynamicTester.js.map +1 -0
  58. package/dist/dynamic/EndpointMapper.js +40 -0
  59. package/dist/dynamic/EndpointMapper.js.map +1 -0
  60. package/dist/dynamic/LocalhostDetector.js +95 -0
  61. package/dist/dynamic/LocalhostDetector.js.map +1 -0
  62. package/dist/dynamic/PerformanceTester.js +60 -0
  63. package/dist/dynamic/PerformanceTester.js.map +1 -0
  64. package/dist/dynamic/SecurityTester.js +165 -0
  65. package/dist/dynamic/SecurityTester.js.map +1 -0
  66. package/dist/dynamic/httpClient.js +45 -0
  67. package/dist/dynamic/httpClient.js.map +1 -0
  68. package/dist/index.js +45 -0
  69. package/dist/index.js.map +1 -0
  70. package/dist/parser/CodeParser.js +198 -0
  71. package/dist/parser/CodeParser.js.map +1 -0
  72. package/dist/parser/DependencyGraph.js +85 -0
  73. package/dist/parser/DependencyGraph.js.map +1 -0
  74. package/dist/parser/EntryPointDetector.js +77 -0
  75. package/dist/parser/EntryPointDetector.js.map +1 -0
  76. package/dist/parser/StackDetector.js +111 -0
  77. package/dist/parser/StackDetector.js.map +1 -0
  78. package/dist/parser/adapters/BabelAdapter.js +170 -0
  79. package/dist/parser/adapters/BabelAdapter.js.map +1 -0
  80. package/dist/parser/adapters/ParserAdapter.js +8 -0
  81. package/dist/parser/adapters/ParserAdapter.js.map +1 -0
  82. package/dist/parser/adapters/PythonAdapter.js +97 -0
  83. package/dist/parser/adapters/PythonAdapter.js.map +1 -0
  84. package/dist/tracker/ChecklistManager.js +40 -0
  85. package/dist/tracker/ChecklistManager.js.map +1 -0
  86. package/dist/tracker/ScoreTracker.js +15 -0
  87. package/dist/tracker/ScoreTracker.js.map +1 -0
  88. package/dist/tracker/StateManager.js +66 -0
  89. package/dist/tracker/StateManager.js.map +1 -0
  90. package/dist/types.js +7 -0
  91. package/dist/types.js.map +1 -0
  92. package/dist/ui/Banner.js +111 -0
  93. package/dist/ui/Banner.js.map +1 -0
  94. package/dist/ui/DeploymentGuide.js +42 -0
  95. package/dist/ui/DeploymentGuide.js.map +1 -0
  96. package/dist/ui/ExportManager.js +103 -0
  97. package/dist/ui/ExportManager.js.map +1 -0
  98. package/dist/ui/FixWalker.js +15 -0
  99. package/dist/ui/FixWalker.js.map +1 -0
  100. package/dist/ui/HtmlReporter.js +140 -0
  101. package/dist/ui/HtmlReporter.js.map +1 -0
  102. package/dist/ui/IssuePresenter.js +73 -0
  103. package/dist/ui/IssuePresenter.js.map +1 -0
  104. package/dist/utils/FileWalker.js +141 -0
  105. package/dist/utils/FileWalker.js.map +1 -0
  106. package/dist/utils/finding.js +47 -0
  107. package/dist/utils/finding.js.map +1 -0
  108. package/dist/utils/logger.js +47 -0
  109. package/dist/utils/logger.js.map +1 -0
  110. package/dist/utils/openBrowser.js +29 -0
  111. package/dist/utils/openBrowser.js.map +1 -0
  112. package/dist/utils/redact.js +83 -0
  113. package/dist/utils/redact.js.map +1 -0
  114. package/docs/sample-config.json +9 -0
  115. package/package.json +61 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Belsoft Solutions
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,136 @@
1
+ # DeployReady
2
+
3
+ > Local-first, AI-optional production-readiness scanner for your app. It runs 30+ structured tests against your code and your running localhost app, then **optionally** sends only the structured findings report — never your source code — to an AI model for deeper analysis.
4
+
5
+ ```
6
+ deployready analyze ./my-app
7
+ ```
8
+
9
+ > 📋 **See [STATUS.md](STATUS.md)** for the full usage guide, step-by-step npm publishing instructions, and an honest, always-current breakdown of what works today vs. what's still to be built.
10
+
11
+ ## Why
12
+
13
+ Research in 2025–2026 found that **~91.5% of "vibe-coded" (AI-generated) apps ship with vulnerabilities**, only **~55%** of AI codegen tasks produce secure code, **86%** fail to defend against XSS, and AI-assisted commits leak secrets at roughly **2× the human baseline**. DeployReady catches those exact failure modes before you deploy.
14
+
15
+ - **Other tools:** send your whole repo to an AI. Expensive, slow, privacy risk.
16
+ - **DeployReady:** run the tests locally first. Send only structured findings to AI (if you want). Expert analysis without the token waste — and it works with no AI at all.
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ npm install -g deployready
22
+ ```
23
+
24
+ ## Usage
25
+
26
+ ### Interactive session (default)
27
+
28
+ Run `deployready` in your project to open a persistent session. You're greeted with an animated welcome and a **guided menu** — no need to know any commands; just pick a number. It stays open and you drive it one step at a time until you `exit`:
29
+
30
+ ```bash
31
+ deployready ./my-app # or just: deployready
32
+ ```
33
+
34
+ ```
35
+ What would you like to do?
36
+ 1 Scan this project now (recommended)
37
+ 2 Set up or change the AI model
38
+ 3 How does DeployReady work?
39
+ 4 Go to the command prompt
40
+ 5 Exit
41
+ ```
42
+
43
+ After any action it suggests your next step (e.g. “type `fix 1` to fix the top issue”). Type `menu` anytime to bring the guide back. Power users can ignore the menu and type commands directly:
44
+
45
+ ```
46
+ deployready › scan # parse → live tests → optional AI
47
+ deployready › issues # list findings, numbered
48
+ deployready › show 3 # full detail of a finding
49
+ deployready › fix 3 # interactive fix: auto-fix, AI-proposed diff, or guidance
50
+ deployready › done 3 # mark fixed (score updates live)
51
+ deployready › deploy aws # deployment walkthrough for your stack
52
+ deployready › export # write deployready-report.md
53
+ deployready › exit
54
+ ```
55
+
56
+ | Command | What it does |
57
+ |---|---|
58
+ | `scan` / `parse` / `dynamic` / `ai` | run the whole pipeline, or one step at a time |
59
+ | `issues [crit\|warn\|info]` · `show <n>` | list findings (filterable) · show one in detail |
60
+ | `fix <n>` | auto-fix where safe; else an AI-proposed diff you approve (creates a backup); else guidance |
61
+ | `done <n>` · `ignore <n>` | mark fixed/ignored — the score recomputes immediately |
62
+ | `score` · `status` · `deploy [aws\|do]` · `export` · `config` · `help` · `exit` | session utilities |
63
+
64
+ ### One-shot (CI / scripting)
65
+
66
+ ```bash
67
+ deployready init # first-time setup (pick model, store key)
68
+ deployready analyze ./my-app # single non-interactive scan, prints results
69
+ deployready analyze . --no-ai --no-dynamic # static only, fully offline
70
+ deployready report ./my-app # scan and export markdown
71
+ deployready analyze . --no-ai --no-dynamic --fail-on critical # CI gate: exit 2 on any critical
72
+ ```
73
+
74
+ One-shot flags: `-y/--yes` (auto-approve prompts), `--aggressive` (rate-limit burst), `--export` (markdown), `--html` + `--open` (HTML dashboard, opened in your browser), `--json` (machine-readable output), `--fail-on <critical|warning|info|none>` (CI exit code), `-v/--verbose`.
75
+
76
+ **CI:** exit codes are `0` (clean), `2` (gate failed), `1` (tool error). A ready-to-copy GitHub Action is in [`docs/github-action-example.yml`](docs/github-action-example.yml).
77
+
78
+ ## Features
79
+
80
+ - **Static analysis** — Babel-based AST parsing (pure JS, no native build), dependency graph, stack detection (Express, Next.js, Fastify, NestJS, Koa, FastAPI, Flask, Django, Laravel).
81
+ - **Secret & vulnerability scanning** — hardcoded credentials, `eval`/command/SQL injection, XSS sinks, weak crypto, insecure randomness, disabled TLS verification, committed `.env`, log injection — each mapped to **OWASP Top 10 (2025)** and **CWE**.
82
+ - **Live dynamic testing** — detects your running localhost app and checks for auth bypass, exposed admin routes, secrets in responses, wildcard CORS, missing security headers, missing rate limiting, slow endpoints, missing cache headers, version-banner and stack-trace leaks.
83
+ - **Production-readiness score (0–100)** with critical/warning/info breakdown.
84
+ - **AI-optional** — works with no key; or send the structured report to Claude, OpenAI, or local Ollama.
85
+ - **Markdown export** to share with your team.
86
+
87
+ ## How It Works
88
+
89
+ ```
90
+ parse → static scan → (you approve) live localhost tests → aggregate + score
91
+ → (you approve) AI analysis of findings JSON → terminal report → export
92
+ ```
93
+
94
+ Only the **structured findings JSON** is ever sent to an AI — and only after you approve, with all secrets redacted first. Ollama runs fully offline.
95
+
96
+ ## Supported AI Models
97
+
98
+ | Model | Notes |
99
+ |---|---|
100
+ | Claude (Anthropic) | Set `ANTHROPIC_API_KEY` or store via `init`. Default: `claude-sonnet-4-6`. |
101
+ | OpenAI | Set `OPENAI_API_KEY` or store via `init`. |
102
+ | Ollama (local) | Fully offline, no key, nothing leaves your machine. |
103
+
104
+ ## Security & Privacy
105
+
106
+ DeployReady is itself built to a high security bar — it reads your code, probes your ports, and holds your keys:
107
+
108
+ - API keys are read from environment variables first and **never logged**. The on-disk config is written with `0600` permissions.
109
+ - All output and any AI payload pass through a central **secret redactor**.
110
+ - Dynamic testing is **loopback-only** and **GET-only** by default; aggressive tests require explicit consent.
111
+ - File scanning is confined to the project root with symlink/traversal protection and size caps.
112
+
113
+ ## Configuration
114
+
115
+ `~/.deployready/config.json` — see [`docs/sample-config.json`](docs/sample-config.json). Prefer env vars for keys.
116
+
117
+ ## Development
118
+
119
+ ```bash
120
+ npm install
121
+ npm run build # tsc -> dist/
122
+ npm test # jest
123
+ npm run dev # run from source via tsx
124
+ ```
125
+
126
+ ## Contributing
127
+
128
+ Issues and PRs welcome. Each module has a single responsibility and a documented interface contract; extend by adding new files rather than modifying existing modules (see the architecture spec).
129
+
130
+ ## Roadmap (Phase 1.5 / 2)
131
+
132
+ Agentic fix application (propose → diff → approve → apply → verify), interactive deployment guides, real-time checklist sidebar, MCP database connectors, GitHub Action, and a compliance module.
133
+
134
+ ---
135
+
136
+ _Belal · Belsoft Solutions · 2026 · MIT License_
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * CLI entry point. Runs the compiled tool; falls back to a clear message if the
4
+ * project hasn't been built yet.
5
+ */
6
+ 'use strict';
7
+
8
+ try {
9
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
10
+ const { run } = require('../dist/index.js');
11
+ run().catch((err) => {
12
+ console.error(err && err.message ? err.message : err);
13
+ process.exit(1);
14
+ });
15
+ } catch (err) {
16
+ if (err && err.code === 'MODULE_NOT_FOUND') {
17
+ console.error('DeployReady is not built yet. Run `npm run build` first (or `npm install -g .`).');
18
+ process.exit(1);
19
+ }
20
+ throw err;
21
+ }
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.FileEditor = void 0;
37
+ /**
38
+ * Safe file read/backup/write for interactive fix application.
39
+ *
40
+ * Safety contract (enforced here):
41
+ * - Every write makes a timestamped backup of the original first.
42
+ * - All access is confined to the scanned project root (no traversal/symlink escape).
43
+ * - Edits are applied by line range (deterministic) — no fuzzy text matching.
44
+ */
45
+ const fs = __importStar(require("fs"));
46
+ const fsp = __importStar(require("fs/promises"));
47
+ const path = __importStar(require("path"));
48
+ class FileEditor {
49
+ projectRoot;
50
+ constructor(projectRoot) {
51
+ this.projectRoot = projectRoot;
52
+ }
53
+ /** Read a file within the project root. */
54
+ async read(relPath) {
55
+ return fsp.readFile(this.resolveSafe(relPath), 'utf8');
56
+ }
57
+ /**
58
+ * Extract the line at `line` (1-based) plus `context` lines on each side.
59
+ * Returns the exact text and the line range it spans.
60
+ */
61
+ async snippet(relPath, line, context = 3) {
62
+ const lines = (await this.read(relPath)).split('\n');
63
+ const start = Math.max(1, line - context);
64
+ const end = Math.min(lines.length, line + context);
65
+ return { text: lines.slice(start - 1, end).join('\n'), startLine: start, endLine: end };
66
+ }
67
+ /**
68
+ * Replace lines [startLine..endLine] (1-based inclusive) with `newText`.
69
+ * Backs up the original first. Returns the backup path.
70
+ */
71
+ async replaceLines(relPath, startLine, endLine, newText) {
72
+ const abs = this.resolveSafe(relPath);
73
+ const original = await fsp.readFile(abs, 'utf8');
74
+ const backup = await this.backup(abs, original);
75
+ const lines = original.split('\n');
76
+ const before = lines.slice(0, startLine - 1);
77
+ const after = lines.slice(endLine);
78
+ const updated = [...before, ...newText.split('\n'), ...after].join('\n');
79
+ await fsp.writeFile(abs, updated, 'utf8');
80
+ return backup;
81
+ }
82
+ /** Append a line to a file (creating it if absent), with backup if it exists. */
83
+ async appendLine(relPath, line) {
84
+ const abs = this.resolveSafe(relPath);
85
+ let backup = null;
86
+ let current = '';
87
+ if (fs.existsSync(abs)) {
88
+ current = await fsp.readFile(abs, 'utf8');
89
+ backup = await this.backup(abs, current);
90
+ }
91
+ const sep = current.length && !current.endsWith('\n') ? '\n' : '';
92
+ await fsp.writeFile(abs, `${current}${sep}${line}\n`, 'utf8');
93
+ return backup;
94
+ }
95
+ fileExists(relPath) {
96
+ try {
97
+ return fs.existsSync(this.resolveSafe(relPath));
98
+ }
99
+ catch {
100
+ return false;
101
+ }
102
+ }
103
+ async backup(abs, contents) {
104
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
105
+ const backup = `${abs}.bak.${stamp}`;
106
+ await fsp.writeFile(backup, contents, 'utf8');
107
+ return backup;
108
+ }
109
+ /** Resolve a path and ensure it stays inside the project root. */
110
+ resolveSafe(relPath) {
111
+ const abs = path.resolve(this.projectRoot, relPath);
112
+ const rel = path.relative(this.projectRoot, abs);
113
+ if (rel.startsWith('..') || path.isAbsolute(rel)) {
114
+ throw new Error(`Refusing to access path outside project: ${relPath}`);
115
+ }
116
+ return abs;
117
+ }
118
+ }
119
+ exports.FileEditor = FileEditor;
120
+ //# sourceMappingURL=FileEditor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FileEditor.js","sourceRoot":"","sources":["../../src/agent/FileEditor.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;GAOG;AACH,uCAAyB;AACzB,iDAAmC;AACnC,2CAA6B;AAS7B,MAAa,UAAU;IACQ;IAA7B,YAA6B,WAAmB;QAAnB,gBAAW,GAAX,WAAW,CAAQ;IAAG,CAAC;IAEpD,2CAA2C;IAC3C,KAAK,CAAC,IAAI,CAAC,OAAe;QACxB,OAAO,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC,CAAC;IACzD,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,OAAO,CAAC,OAAe,EAAE,IAAY,EAAE,OAAO,GAAG,CAAC;QACtD,MAAM,KAAK,GAAG,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACrD,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO,CAAC,CAAC;QAC1C,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,GAAG,OAAO,CAAC,CAAC;QACnD,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC;IAC1F,CAAC;IAED;;;OAGG;IAC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ACD,OAAO,GAAG,CAAC;IACb,CAAC;CACF;AA1ED,gCA0EC"}
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FixManager = void 0;
4
+ const AUTO_FIXABLE = new Set(['env-not-ignored']);
5
+ class FixManager {
6
+ /** True if this finding has a safe, deterministic auto-fix. */
7
+ static autoFixable(finding) {
8
+ return AUTO_FIXABLE.has(finding.rule);
9
+ }
10
+ /** Apply a safe deterministic fix. Throws if the rule isn't auto-fixable. */
11
+ static async autoFix(finding, editor) {
12
+ if (finding.rule === 'env-not-ignored') {
13
+ const existing = editor.fileExists('.gitignore') ? await editor.read('.gitignore') : '';
14
+ if (/(^|\n)\s*\.env\s*($|\n)/.test(existing)) {
15
+ return { message: '.gitignore already contains .env — no change needed.', backup: null };
16
+ }
17
+ const backup = await editor.appendLine('.gitignore', '.env');
18
+ return {
19
+ message: 'Added `.env` to .gitignore. NOTE: also remove it from git history and rotate any committed secrets.',
20
+ backup,
21
+ };
22
+ }
23
+ throw new Error(`No automatic fix available for rule "${finding.rule}".`);
24
+ }
25
+ /** True if we can attempt an AI fix (finding points at a concrete file+line). */
26
+ static aiFixable(finding) {
27
+ return Boolean(finding.file && finding.line);
28
+ }
29
+ /** Read the snippet around the finding for an AI rewrite. */
30
+ static async snippetFor(finding, editor) {
31
+ if (!finding.file || !finding.line)
32
+ throw new Error('This finding has no file/line to fix.');
33
+ return editor.snippet(finding.file, finding.line);
34
+ }
35
+ /** Ask the model for a corrected snippet (sends the redacted snippet). */
36
+ static async aiSuggest(finding, snippet, router) {
37
+ return router.suggestFix(finding, snippet.text);
38
+ }
39
+ /** Apply an approved suggestion to disk (backs up first). Returns backup path. */
40
+ static async applySuggestion(finding, snippet, newCode, editor) {
41
+ if (!finding.file)
42
+ throw new Error('This finding has no file to write.');
43
+ return editor.replaceLines(finding.file, snippet.startLine, snippet.endLine, newCode);
44
+ }
45
+ }
46
+ exports.FixManager = FixManager;
47
+ //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,EAAE,MAAkB;QAC1D,IAAI,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI;YAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;QAC7F,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IACpD,CAAC;IAED,0EAA0E;IAC1E,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,OAAgB,EAAE,OAAgB,EAAE,MAAmB;QAC5E,OAAO,MAAM,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IAClD,CAAC;IAED,kFAAkF;IAClF,MAAM,CAAC,KAAK,CAAC,eAAe,CAC1B,OAAgB,EAChB,OAAgB,EAChB,OAAe,EACf,MAAkB;QAElB,IAAI,CAAC,OAAO,CAAC,IAAI;YAAE,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;QACzE,OAAO,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IACxF,CAAC;CACF;AAhDD,gCAgDC"}
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SessionManager = void 0;
4
+ class SessionManager {
5
+ _report;
6
+ _config;
7
+ constructor(_report, _config) {
8
+ this._report = _report;
9
+ this._config = _config;
10
+ }
11
+ async start() {
12
+ throw new Error('Interactive agentic session ships in Phase 1.5.');
13
+ }
14
+ }
15
+ exports.SessionManager = SessionManager;
16
+ //# sourceMappingURL=SessionManager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SessionManager.js","sourceRoot":"","sources":["../../src/agent/SessionManager.ts"],"names":[],"mappings":";;;AASA,MAAa,cAAc;IAEN;IACA;IAFnB,YACmB,OAAmB,EACnB,OAAkB;QADlB,YAAO,GAAP,OAAO,CAAY;QACnB,YAAO,GAAP,OAAO,CAAW;IAClC,CAAC;IAEJ,KAAK,CAAC,KAAK;QACT,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACrE,CAAC;CACF;AATD,wCASC"}
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SystemPrompt = void 0;
4
+ class SystemPrompt {
5
+ static build(_report) {
6
+ throw new Error('Agentic session (SystemPrompt) ships in Phase 1.5.');
7
+ }
8
+ }
9
+ exports.SystemPrompt = SystemPrompt;
10
+ //# sourceMappingURL=SystemPrompt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SystemPrompt.js","sourceRoot":"","sources":["../../src/agent/SystemPrompt.ts"],"names":[],"mappings":";;;AAQA,MAAa,YAAY;IACvB,MAAM,CAAC,KAAK,CAAC,OAAmB;QAC9B,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;IACxE,CAAC;CACF;AAJD,oCAIC"}
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ToolDispatcher = void 0;
4
+ /**
5
+ * Phase 1.5 — Routes AI tool-call requests (run_security_test, read_file,
6
+ * propose_fix, etc.) to the correct module. Stub for the MVP.
7
+ */
8
+ class ToolDispatcher {
9
+ async dispatch(_tool, _args) {
10
+ throw new Error('Agentic tool dispatch ships in Phase 1.5.');
11
+ }
12
+ }
13
+ exports.ToolDispatcher = ToolDispatcher;
14
+ //# sourceMappingURL=ToolDispatcher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ToolDispatcher.js","sourceRoot":"","sources":["../../src/agent/ToolDispatcher.ts"],"names":[],"mappings":";;;AAAA;;;GAGG;AACH,MAAa,cAAc;IACzB,KAAK,CAAC,QAAQ,CAAC,KAAa,EAAE,KAA8B;QAC1D,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;IAC/D,CAAC;CACF;AAJD,wCAIC"}
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ClaudeHandler = void 0;
7
+ exports.describeHttpError = describeHttpError;
8
+ /**
9
+ * Anthropic (Claude) API handler. Never import this directly outside
10
+ * ModelRouter — all AI calls funnel through the router.
11
+ */
12
+ const axios_1 = __importDefault(require("axios"));
13
+ const parseAiResponse_1 = require("./parseAiResponse");
14
+ const API_URL = 'https://api.anthropic.com/v1/messages';
15
+ const DEFAULT_MODEL = 'claude-sonnet-4-6';
16
+ const ANTHROPIC_VERSION = '2023-06-01';
17
+ class ClaudeHandler {
18
+ apiKey;
19
+ model;
20
+ /** Context window we target when chunking (Claude handles far more, but keep prompts lean). */
21
+ static contextTokens = 100_000;
22
+ constructor(apiKey, model = DEFAULT_MODEL) {
23
+ this.apiKey = apiKey;
24
+ this.model = model;
25
+ }
26
+ async analyze(prompt) {
27
+ return (0, parseAiResponse_1.parseAiResponse)(await this.complete(prompt));
28
+ }
29
+ /** Raw text completion — used for fix suggestions and analysis alike. */
30
+ async complete(prompt) {
31
+ try {
32
+ const res = await axios_1.default.post(API_URL, {
33
+ model: this.model,
34
+ max_tokens: 4096,
35
+ system: prompt.system,
36
+ messages: [{ role: 'user', content: prompt.user }],
37
+ }, {
38
+ timeout: 60_000,
39
+ headers: {
40
+ 'x-api-key': this.apiKey,
41
+ 'anthropic-version': ANTHROPIC_VERSION,
42
+ 'content-type': 'application/json',
43
+ },
44
+ });
45
+ return (res.data?.content ?? [])
46
+ .filter((b) => b.type === 'text')
47
+ .map((b) => b.text)
48
+ .join('\n');
49
+ }
50
+ catch (err) {
51
+ throw new Error(`Claude API request failed: ${describeHttpError(err)}`);
52
+ }
53
+ }
54
+ }
55
+ exports.ClaudeHandler = ClaudeHandler;
56
+ /** Produce a safe, human-readable error without leaking the key or full body. */
57
+ function describeHttpError(err) {
58
+ if (axios_1.default.isAxiosError(err)) {
59
+ if (err.response) {
60
+ const status = err.response.status;
61
+ if (status === 401 || status === 403)
62
+ return 'authentication failed (check your API key)';
63
+ if (status === 429)
64
+ return 'rate limited (too many requests)';
65
+ return `server returned ${status}`;
66
+ }
67
+ if (err.code === 'ECONNABORTED')
68
+ return 'request timed out';
69
+ return err.message;
70
+ }
71
+ return err.message ?? 'unknown error';
72
+ }
73
+ //# sourceMappingURL=ClaudeHandler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ClaudeHandler.js","sourceRoot":"","sources":["../../src/ai/ClaudeHandler.ts"],"names":[],"mappings":";;;;;;AAyDA,8CAYC;AArED;;;GAGG;AACH,kDAA0B;AAC1B,uDAAoD;AAIpD,MAAM,OAAO,GAAG,uCAAuC,CAAC;AACxD,MAAM,aAAa,GAAG,mBAAmB,CAAC;AAC1C,MAAM,iBAAiB,GAAG,YAAY,CAAC;AAEvC,MAAa,aAAa;IAKL;IACA;IALnB,+FAA+F;IAC/F,MAAM,CAAU,aAAa,GAAG,OAAO,CAAC;IAExC,YACmB,MAAc,EACd,QAAgB,aAAa;QAD7B,WAAM,GAAN,MAAM,CAAQ;QACd,UAAK,GAAL,KAAK,CAAwB;IAC7C,CAAC;IAEJ,KAAK,CAAC,OAAO,CAAC,MAAmB;QAC/B,OAAO,IAAA,iCAAe,EAAC,MAAM,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;IACtD,CAAC;IAED,yEAAyE;IACzE,KAAK,CAAC,QAAQ,CAAC,MAAmB;QAChC,IAAI,CAAC;YACH,MAAM,GAAG,GAAG,MAAM,eAAK,CAAC,IAAI,CAC1B,OAAO,EACP;gBACE,KAAK,EAAE,IAAI,CAAC,KAAK;gBACjB,UAAU,EAAE,IAAI;gBAChB,MAAM,EAAE,MAAM,CAAC,MAAM;gBACrB,QAAQ,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,E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@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ContextChunker = void 0;
4
+ const CHARS_PER_TOKEN = 4;
5
+ class ContextChunker {
6
+ /**
7
+ * Return a report whose findings list is trimmed so the serialized payload
8
+ * stays under `maxTokens`. Highest-severity findings are kept first.
9
+ */
10
+ static fit(report, maxTokens) {
11
+ const budgetChars = maxTokens * CHARS_PER_TOKEN;
12
+ if (JSON.stringify(report.findings).length <= budgetChars)
13
+ return report;
14
+ const order = { critical: 0, warning: 1, info: 2 };
15
+ const sorted = [...report.findings].sort((a, b) => order[a.severity] - order[b.severity]);
16
+ const kept = [];
17
+ let size = 0;
18
+ for (const f of sorted) {
19
+ const cost = JSON.stringify(f).length;
20
+ if (size + cost > budgetChars)
21
+ break;
22
+ kept.push(f);
23
+ size += cost;
24
+ }
25
+ return { ...report, findings: kept };
26
+ }
27
+ }
28
+ exports.ContextChunker = ContextChunker;
29
+ //# sourceMappingURL=ContextChunker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ContextChunker.js","sourceRoot":"","sources":["../../src/ai/ContextChunker.ts"],"names":[],"mappings":";;;AAOA,MAAM,eAAe,GAAG,CAAC,CAAC;AAE1B,MAAa,cAAc;IACzB;;;OAGG;IACH,MAAM,CAAC,GAAG,CAAC,MAAkB,EAAE,SAAiB;QAC9C,MAAM,WAAW,GAAG,SAAS,GAAG,eAAe,CAAC;QAChD,IAAI,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,MAAM,IAAI,WAAW;YAAE,OAAO,MAAM,CAAC;QAEzE,MAAM,KAAK,GAAG,EAAE,QAAQ,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAW,CAAC;QAC5D,MAAM,MAAM,GAAG,CAAC,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;QAE1F,MAAM,IAAI,GAAkB,EAAE,CAAC;QAC/B,IAAI,IAAI,GAAG,CAAC,CAAC;QACb,KAAK,MAAM,CAAC,IAAI,MAAM,EAAE,CAAC;YACvB,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;YACtC,IAAI,IAAI,GAAG,IAAI,GAAG,WAAW;gBAAE,MAAM;YACrC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YACb,IAAI,IAAI,IAAI,CAAC;QACf,CAAC;QACD,OAAO,EAAE,GAAG,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;IACvC,CAAC;CACF;AAtBD,wCAsBC"}
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ModelRouter = void 0;
4
+ /**
5
+ * Single entry point for all AI analysis. Picks the right handler from config,
6
+ * builds + chunks the prompt, and returns structured findings.
7
+ *
8
+ * CRITICAL: every other module talks to AI through here — never import the
9
+ * individual handlers directly.
10
+ *
11
+ * Interface contract:
12
+ * const router = new ModelRouter(config);
13
+ * const analysis = await router.analyze(report);
14
+ */
15
+ const ClaudeHandler_1 = require("./ClaudeHandler");
16
+ const OpenAIHandler_1 = require("./OpenAIHandler");
17
+ const OllamaHandler_1 = require("./OllamaHandler");
18
+ const PromptBuilder_1 = require("./PromptBuilder");
19
+ const ContextChunker_1 = require("./ContextChunker");
20
+ const ConfigManager_1 = require("../config/ConfigManager");
21
+ const redact_1 = require("../utils/redact");
22
+ const parseFix_1 = require("./parseFix");
23
+ class ModelRouter {
24
+ config;
25
+ constructor(config) {
26
+ this.config = config;
27
+ }
28
+ /** True if data will leave the machine for this model (i.e. not Ollama). */
29
+ get sendsExternally() {
30
+ return this.config.model !== 'ollama';
31
+ }
32
+ /** Whether a usable handler can be constructed (key present, etc.). */
33
+ isConfigured() {
34
+ if (this.config.model === 'ollama')
35
+ return true;
36
+ return Boolean(ConfigManager_1.ConfigManager.resolveKey(this.config));
37
+ }
38
+ /** Exactly what would be sent externally, for the consent prompt. */
39
+ previewPayload(report) {
40
+ return PromptBuilder_1.PromptBuilder.preview(report);
41
+ }
42
+ async analyze(report) {
43
+ const { handler, contextTokens } = this.resolveHandler();
44
+ const fitted = ContextChunker_1.ContextChunker.fit(report, contextTokens);
45
+ const prompt = PromptBuilder_1.PromptBuilder.build(fitted);
46
+ return handler.analyze(prompt);
47
+ }
48
+ /**
49
+ * Ask the model to rewrite `snippet` to fix `finding`. The snippet is redacted
50
+ * before sending. Caller is responsible for obtaining the user's consent.
51
+ */
52
+ async suggestFix(finding, snippet) {
53
+ const { handler } = this.resolveHandler();
54
+ const prompt = PromptBuilder_1.PromptBuilder.buildFixPrompt(finding, (0, redact_1.redact)(snippet));
55
+ const raw = await handler.complete(prompt);
56
+ const parsed = (0, parseFix_1.extractFix)(raw);
57
+ if (!parsed)
58
+ throw new Error('The model did not return a usable fix.');
59
+ return parsed;
60
+ }
61
+ resolveHandler() {
62
+ switch (this.config.model) {
63
+ case 'claude': {
64
+ const key = ConfigManager_1.ConfigManager.resolveKey(this.config);
65
+ if (!key)
66
+ throw new Error('No Claude API key configured. Run `deployready init` or set ANTHROPIC_API_KEY.');
67
+ return { handler: new ClaudeHandler_1.ClaudeHandler(key), contextTokens: ClaudeHandler_1.ClaudeHandler.contextTokens };
68
+ }
69
+ case 'openai': {
70
+ const key = ConfigManager_1.ConfigManager.resolveKey(this.config);
71
+ if (!key)
72
+ throw new Error('No OpenAI API key configured. Run `deployready init` or set OPENAI_API_KEY.');
73
+ return { handler: new OpenAIHandler_1.OpenAIHandler(key), contextTokens: OpenAIHandler_1.OpenAIHandler.contextTokens };
74
+ }
75
+ case 'ollama':
76
+ return {
77
+ handler: new OllamaHandler_1.OllamaHandler(this.config.ollamaPort, this.config.ollamaModel),
78
+ contextTokens: OllamaHandler_1.OllamaHandler.contextTokens,
79
+ };
80
+ default:
81
+ throw new Error(`Unknown model: ${String(this.config.model)}`);
82
+ }
83
+ }
84
+ }
85
+ exports.ModelRouter = ModelRouter;
86
+ //# sourceMappingURL=ModelRouter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ModelRouter.js","sourceRoot":"","sources":["../../src/ai/ModelRouter.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;GAUG;AACH,mDAAgD;AAChD,mDAAgD;AAChD,mDAAgD;AAChD,mDAAgD;AAChD,qDAAkD;AAClD,2DAAwD;AACxD,4CAAyC;AACzC,yCAA4D;AAU5D,MAAa,WAAW;IACO;IAA7B,YAA6B,MAAiB;QAAjB,WAAM,GAAN,MAAM,CAAW;IAAG,CAAC;IAElD,4EAA4E;IAC5E,IAAI,eAAe;QACjB,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,KAAK,QAAQ,CAAC;IACxC,CAAC;IAED,uEAAuE;IACvE,YAAY;QACV,IAAI,IAAI,CAAC,MAAM,CAAC,KAAK,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAC;QAChD,OAAO,OAAO,CAAC,6BAAa,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;IACxD,CAAC;IAED,qEAAqE;IACrE,cAAc,CAAC,MAAkB;QAC/B,OAAO,6BAAa,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACvC,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,MAAkB;QAC9B,MAAM,EAAE,OAAO,EAAE,aAAa,EAAE,GAAG,IAAI,CAAC,cAAc,EAAE,CAAC;QACzD,MAAM,MAAM,GAAG,+BAAc,CAAC,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;QACzD,MAAM,MAAM,GAAG,6BAAa,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAC3C,OAAO,OAAO,CAAC,OAAO,CAAC,M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