@ipul-labs/forge 1.16.4 → 1.16.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli/repl.js CHANGED
@@ -1,13 +1,15 @@
1
1
  import readline from "node:readline";
2
+ import { execSync } from "node:child_process";
2
3
  import path from "node:path";
3
- import { projectRoot, readPkg, resolvePrimaryRepo } from "./utils.js";
4
+ import { projectRoot, readPkg, resolvePrimaryRepo, relativeAge } from "./utils.js";
5
+ import { getHead, readState, listSessions } from "./sessionStore.js";
4
6
 
5
7
  const COMMANDS = [
6
8
  "ship", "init", "start", "repos", "issues", "issue", "create-issue",
7
9
  "analyze", "show", "refine", "validate", "apply", "watch",
8
10
  "ci-fix", "merge", "resolution-check", "close",
9
- "session", "doctor", "update", "use", "version", "help",
10
- "exit", "quit", "clear",
11
+ "session", "doctor", "update", "use", "status", "open", "log",
12
+ "version", "help", "exit", "quit", "clear",
11
13
  ];
12
14
 
13
15
  class ExitInterrupt extends Error {
@@ -154,6 +156,73 @@ export async function startRepl(dispatch) {
154
156
 
155
157
  const argv = parseInput(trimmed);
156
158
 
159
+ if (argv[0] === "status") {
160
+ process.stdout.write("\n");
161
+ const head = await getHead();
162
+ if (!head) {
163
+ process.stdout.write(`${DIM}No active session. Run: analyze <iid>${RESET}\n`);
164
+ } else {
165
+ const state = await readState(head.repo, head.iid);
166
+ if (!state) {
167
+ process.stdout.write(`${DIM}Session ${head.repo}#${head.iid} — no state${RESET}\n`);
168
+ } else {
169
+ process.stdout.write(`${YELLOW}${state.repo || head.repo}${RESET} ${BOLD}#${state.iid || head.iid}${RESET}\n`);
170
+ process.stdout.write(`${DIM}phase${RESET} ${state.phase || "unknown"}\n`);
171
+ if (state.branch) process.stdout.write(`${DIM}branch${RESET} ${state.branch}\n`);
172
+ if (state.mrUrl) process.stdout.write(`${DIM}mr${RESET} ${state.mrUrl}\n`);
173
+ if (state.lastPipelineStatus) process.stdout.write(`${DIM}ci${RESET} ${state.lastPipelineStatus}\n`);
174
+ if (state.updatedAt) process.stdout.write(`${DIM}updated${RESET} ${relativeAge(state.updatedAt)} ago\n`);
175
+ }
176
+ }
177
+ process.stdout.write("\n");
178
+ showPrompt();
179
+ continue;
180
+ }
181
+
182
+ if (argv[0] === "open") {
183
+ const head = await getHead();
184
+ if (!head) {
185
+ process.stdout.write(`${DIM}No active session.${RESET}\n`);
186
+ } else {
187
+ const state = await readState(head.repo, head.iid);
188
+ const url = argv[1] === "mr" && state?.mrUrl
189
+ ? state.mrUrl
190
+ : state?.issueUrl || state?.mrUrl;
191
+ if (url) {
192
+ try { execSync(`open "${url}"`); } catch {}
193
+ process.stdout.write(`${DIM}Opened ${url}${RESET}\n`);
194
+ } else {
195
+ process.stdout.write(`${DIM}No URL found. Run: analyze <iid>${RESET}\n`);
196
+ }
197
+ }
198
+ showPrompt();
199
+ continue;
200
+ }
201
+
202
+ if (argv[0] === "log") {
203
+ const sessions = await listSessions();
204
+ if (sessions.length === 0) {
205
+ process.stdout.write(`\n${DIM}No sessions.${RESET}\n\n`);
206
+ } else {
207
+ const head = await getHead();
208
+ const limit = Math.min(sessions.length, 10);
209
+ process.stdout.write("\n");
210
+ for (let i = 0; i < limit; i++) {
211
+ const s = sessions[i];
212
+ const isHead = head && s.repo === head.repo && s.iid === head.iid;
213
+ const marker = isHead ? `${GREEN}*${RESET} ` : " ";
214
+ const age = relativeAge(s.updatedAt);
215
+ process.stdout.write(`${marker}${YELLOW}#${s.iid}${RESET} ${s.phase || "?"} ${DIM}${s.repo} ${age}${RESET}\n`);
216
+ }
217
+ if (sessions.length > limit) {
218
+ process.stdout.write(`${DIM} ...${sessions.length - limit} more${RESET}\n`);
219
+ }
220
+ process.stdout.write("\n");
221
+ }
222
+ showPrompt();
223
+ continue;
224
+ }
225
+
157
226
  if (argv[0] === "use") {
158
227
  process.stdout.write("\n");
159
228
  if (!argv[1]) {
@@ -58,6 +58,9 @@ Commands
58
58
  resolution-check Verify the merged MR actually closes the issue
59
59
  close [<iid>] Close the issue (confirms by default)
60
60
  use <repo> Switch active repo (interactive mode)
61
+ status Show current session (issue, phase, branch, MR)
62
+ open [mr] Open current issue or MR in browser
63
+ log List recent sessions with phase and age
61
64
  session Inspect cached sessions (list | show | clean)
62
65
  doctor Check prerequisites (node, git, claude CLI, token, config)
63
66
  update Pull latest changes + reinstall dependencies
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ipul-labs/forge",
3
- "version": "1.16.4",
3
+ "version": "1.16.6",
4
4
  "description": "AI-powered code change & deploy control panel — connects Claude, GitLab, and Kubernetes",
5
5
  "readmeFilename": "README.md",
6
6
  "type": "module",
7
7
  "main": "server/forge/routes.js",
8
8
  "bin": {
9
- "forge": "./bin/forge-agent.js"
9
+ "forge": "bin/forge-agent.js"
10
10
  },
11
11
  "exports": {
12
12
  ".": "./server/forge/routes.js",
@@ -16,6 +16,7 @@
16
16
  "files": [
17
17
  "README.md",
18
18
  "bin",
19
+ "scripts",
19
20
  "server/forge",
20
21
  "dist"
21
22
  ],
@@ -26,7 +27,7 @@
26
27
  "typecheck": "tsc --noEmit",
27
28
  "test": "vitest run",
28
29
  "test:watch": "vitest",
29
- "prepack": "node -e \"const p=require('./package.json'),fs=require('fs');p.readme=fs.readFileSync('README.md','utf8');fs.writeFileSync('package.json',JSON.stringify(p,null,2)+'\\n')\""
30
+ "prepack": "node scripts/inject-readme.cjs"
30
31
  },
31
32
  "dependencies": {
32
33
  "@kubernetes/client-node": "^1.0.0",
@@ -77,7 +78,7 @@
77
78
  },
78
79
  "repository": {
79
80
  "type": "git",
80
- "url": "https://gitlab.com/ipul-labs/forge.git"
81
+ "url": "git+https://gitlab.com/ipul-labs/forge.git"
81
82
  },
82
83
  "license": "MIT",
83
84
  "readme": "# Forge by iPuL\n\nAI-powered code change & deploy control panel. Connect an issue tracker, let Claude propose a fix, review the diff, approve — and Forge creates the branch, commits the changes, opens the MR/PR, and monitors the CI pipeline.\n\nBuilt on: Claude Code CLI · GitLab / GitHub / Azure DevOps · Kubernetes\n\n---\n\n## Why Forge\n\n**The CI refinement loop is the thing.** Every other AI coding tool hands off after the PR is open. Forge keeps going: when your pipeline fails, it grabs the last 150 lines of the failed job log, feeds them back to Claude with the original fix context, generates a targeted patch, and commits it to the branch — automatically. No human has to read the stack trace, translate it into a prompt, and paste it somewhere. The loop closes itself.\n\nEverything else fills in the gaps that matter for real teams:\n\n- **No per-token cost** — Claude runs via the `claude` CLI using your existing Claude subscription, not API credits. Heavy use doesn't trigger a bill.\n- **Multi-provider** — GitLab, GitHub, and Azure DevOps are all first-class. Switch providers with a single env var; all normalized data shapes stay the same.\n- **Self-hosted** — your code never leaves your infrastructure. The backend runs wherever you deploy it; AI calls go to Anthropic (or a local gateway via OpenClaw).\n- **Two-pass analysis keeps context focused** — Claude first identifies the 6 most relevant files, then reads only those when proposing the fix. This produces sharper diffs than dumping the whole repo into one prompt.\n\n---\n\n## How it works\n\n1. **Connect** — enter your Forge token to authenticate\n2. **Pick an issue** — Forge loads open issues from your project\n3. **Analyze** — Claude reads the repo file tree, identifies relevant files, and proposes a targeted fix\n4. **Review** — inspect the diff file-by-file; refine with natural-language feedback if needed\n5. **Apply** — Forge creates a branch, commits all changes, and opens a merge/pull request\n6. **Monitor** — watch the CI pipeline run; if it fails, click \"Fix with AI\" to iterate\n\n---\n\n## Getting started\n\n### Prerequisites\n\n- Node.js 20+\n- `claude` CLI installed and authenticated (`claude auth login`)\n- Credentials for your SCM provider (see [Configuration](#configuration))\n\n### Install\n\n```bash\ngit clone https://gitlab.com/ipul-labs/forge.git\ncd forge\nnpm install\n```\n\n### Configure\n\n```bash\n# Interactive setup — writes .env and ~/.forge/config.json\nnpx forge init\n```\n\nOr copy the example env and fill in the values manually:\n\n```bash\ncp .env.example .env\n# fill in FORGE_TOKEN plus your provider credentials\n```\n\n### Launch the UI\n\n```bash\nnpm run dev\n# opens http://localhost:5000 (frontend) with API on :5001\n```\n\nFor production:\n\n```bash\nnpm run build:app # builds Vite SPA to dist/\nnpm start # NODE_ENV=production node server.js\n```\n\n### CLI usage\n\nThe `forge` CLI drives the same orchestrator from the terminal. Install globally or use `npx`:\n\n```bash\n# Global install (adds `forge` to PATH)\nnpm install -g @ipul-labs/forge\n\n# Or run via npx from the repo\nnpx forge <command>\n```\n\n#### Interactive mode\n\nRun `forge` with no arguments to enter an interactive terminal session:\n\n```bash\nforge\n```\n\n```\n forge v1.15.1\n\n──────────────────────────────────────────────────\n ❯ issues --limit 5\n──────────────────────────────────────────────────\n group/repo | agent:claude | v1.15.1\n```\n\nTab-completes command names. Type `use <repo>` to switch repos. Commands that error stay in the session — only `exit`, `quit`, or Ctrl+D leave.\n\n#### End-to-end: issue to production\n\n```bash\nforge ship 42\n```\n\nRuns: analyze → review → validate → apply → watch CI → merge → watch deploy → close, with a `y/N` gate at every state-changing step.\n\n#### Step-by-step commands\n\n```bash\nforge issues # List open issues (--label X, --mine, --limit N)\nforge issue 42 # Show full description\nforge create-issue --title \"fix: broken widget\" # Create a new issue\nforge analyze 42 # Run two-pass analysis, cache result\nforge show # Re-render cached analysis\nforge refine --feedback \"...\" # Iterate with feedback\nforge validate # Run lint/typecheck/test against proposed changes\nforge apply # Push branch + open MR\nforge watch # Poll the MR pipeline\nforge ci-fix # Re-analyze with failed-pipeline logs\nforge merge # Merge the MR\nforge resolution-check # Verify merged MR closes the issue\nforge close # Close the issue\nforge use group/other-repo # Switch active repo\nforge update # Pull latest + reinstall dependencies\n```\n\n#### Options\n\n```\n-p, --port <n> Port for start\n--repo <group/repo> Primary repo\n--secondary <repo> Additional repo (repeatable)\n--all-repos Include every configured repo\n--model <id> Claude model override\n--agent <name> Agent backend: claude | openclaw\n--prompt <text> Extra user prompt\n--json JSON output\n--quiet Suppress progress\n--yes Skip confirmation gates\n--validate Run validate before apply\n```\n\n#### Diagnostics\n\n```bash\nforge doctor # Check prerequisites (node, claude CLI, env vars)\nforge session list # List cached sessions\nforge session clean # Remove stale session data\n```\n\nSee [`docs/cli.md`](./docs/cli.md) for the full command reference and [`docs/cli-ship-workflow.md`](./docs/cli-ship-workflow.md) for the workflow design.\n\n---\n\n## Configuration\n\n### Core\n\n| Variable | Required | Description |\n|---|---|---|\n| `FORGE_TOKEN` | Yes | Dashboard password — also auto-fills the UI login form |\n| `FORGE_REPOS` | Yes | Comma-separated repo list; first entry is the primary project |\n| `SCM_PROVIDER` | — | `gitlab` (default) · `github` · `azuredevops` |\n| `ANTHROPIC_API_KEY` | — | Enables live model list from Anthropic; falls back to hardcoded list |\n| `FORGE_MODEL` | — | Override default model (default: `claude-sonnet-4-6`) |\n| `K8S_CLUSTER_TOKEN` | — | K8s service account token for rollout monitoring |\n| `K8S_CLUSTER_SERVER` | — | K8s API server URL |\n| `PORT` | — | HTTP server port (default: `5001`) |\n| `OPENCLAW_GATEWAY_URL` | — | Enables OpenClaw agent backend; point at your local Gateway |\n| `OPENCLAW_TOKEN` | — | Bearer token for OpenClaw Gateway auth |\n\n### Provider credentials\n\nSCM tokens can be set here **or** in the Forge Settings UI (Settings → Connections). The UI value takes precedence over env vars.\n\n#### GitLab (`SCM_PROVIDER=gitlab`, default)\n\n| Variable | Required | Description |\n|---|---|---|\n| `GITLAB_TOKEN` | Yes | Personal access token with `api` + `write_repository` scopes |\n\n#### GitHub (`SCM_PROVIDER=github`)\n\n| Variable | Required | Description |\n|---|---|---|\n| `GITHUB_TOKEN` | Yes | Personal access token with `repo` + `workflow` scopes |\n| `GITHUB_OWNER` | Yes | Organization or user, e.g. `ipul-labs` |\n| `GITHUB_REPO` | Yes | Repository name, e.g. `web-app` |\n| `GITHUB_BASE_BRANCH` | — | Default target branch (default: `main`) |\n\n#### Azure DevOps (`SCM_PROVIDER=azuredevops`)\n\n| Variable | Required | Description |\n|---|---|---|\n| `AZURE_DEVOPS_TOKEN` | Yes | Personal access token (Full access or Code + Work Items) |\n| `AZURE_DEVOPS_ORG` | Yes | Organization name, e.g. `ipul-labs` |\n| `AZURE_DEVOPS_PROJECT` | Yes | Team project name, e.g. `web-app` |\n| `AZURE_DEVOPS_REPO` | — | Git repo name (defaults to project name) |\n| `AZURE_DEVOPS_BASE_BRANCH` | — | Default target branch (default: `main`) |\n\n### Deprecated (still work as fallbacks)\n\n| Variable | Replaced by |\n|---|---|\n| `FORGE_GITLAB_PROJECT` | First entry in `FORGE_REPOS` |\n| `VITE_FORGE_TOKEN` | Auto-derived from `FORGE_TOKEN` |\n| `FORGE_REFINE_REPO_ACCESS` | Settings UI toggle (Settings → Defaults) |\n\nSee `.env.example` for a full annotated list.\n\n---\n\n## Multi-provider support\n\nForge's SCM layer is a clean provider abstraction — all three providers implement the same `ScmProvider` interface and return identical normalized shapes (`NormalIssue`, `NormalMR`, `NormalPipeline`, etc.). The rest of the codebase never knows which provider is active.\n\n### Switching providers\n\n```bash\n# .env\nSCM_PROVIDER=github\nGITHUB_TOKEN=ghp_...\nGITHUB_OWNER=my-org\nGITHUB_REPO=my-repo\n```\n\n### Per-repo prefix (multi-repo mixed-provider setups)\n\n```bash\nFORGE_REPOS=gitlab:ipul/web-app,github:my-org/mobile\n```\n\n### Provider capabilities\n\n| Feature | GitLab | GitHub | Azure DevOps |\n|---|---|---|---|\n| Issues / Work Items | Yes | Yes | Yes (Work Items) |\n| Multi-file commits | Yes | Yes (Git Data API) | Yes (Pushes API) |\n| Merge / Pull Requests | Yes | Yes | Yes |\n| CI pipelines | Yes (GitLab CI) | Yes (GitHub Actions) | Yes (Azure Pipelines) |\n| Job log traces | Yes | Yes | Yes |\n| Server-side rebase | Yes | — | — |\n\n---\n\n## Production deployment\n\n```bash\nnpm run build:app # builds Vite SPA to dist/\nNODE_ENV=production node server.js\n```\n\nOr with Docker:\n\n```bash\ndocker build -t forge .\ndocker run -p 5001:5001 --env-file .env forge\n```\n\n---\n\n## Architecture\n\n```\nbin/\n forge-agent.js # CLI entry point (forge command)\n cli/\n ship.js # End-to-end orchestrator (Ink UI)\n analyze.js # Two-pass issue analysis\n resolution.js # Post-merge resolution check\n sessionStore.js # ~/.forge/sessions/ persistence\n ...\n\nserver/\n forge/\n routes.js # Express router — all /api/forge/* endpoints\n core/\n ForgeAgent.js # Orchestrates the full pipeline (analyze -> apply -> refine)\n claudeClient.js # Shells out to the claude CLI for structured output\n openclawClient.js # OpenClaw Gateway HTTP client\n agentClient.js # Dispatcher: routes to claudeClient or openclawClient\n k8s.js # Kubernetes client for rollout monitoring\n providers/\n base.js # Abstract ScmProvider — normalized shapes + interface\n gitlab.js # GitLab REST API v4\n github.js # GitHub REST API v3 + Git Data API\n azuredevops.js # Azure DevOps REST API\n index.js # createProvider() factory\n\nsrc/\n views/Forge/\n ForgeDashboard.tsx # Root UI component with tabbed issue/MR views\n api.ts # Token management + fetch helper\n types.ts # Shared TypeScript types\n utils.ts # SSE helper + state utilities\n components/ # Analysis progress, pipeline status, diff viewer\n hooks/\n useForgeDashboard.ts # All state, phase transitions, and API calls\n```\n\n### Two-pass analysis\n\n**Pass 1** — `identifyRelevantFiles`: Claude reads the issue + file tree, returns the max-6 most relevant paths.\n\n**Pass 2** — `proposeFix`: Claude reads the actual file contents and proposes a targeted fix as a JSON diff.\n\nBoth passes use `claude --print --output-format json` so cost and service tier are tracked automatically.\n\n### CI refinement\n\nWhen a pipeline fails, Forge fetches the last 150 lines of each failed job's trace log and feeds them to pass 2 with an explicit \"pipeline failed\" framing — not generic reviewer feedback. This improves fix quality for common failures like lint errors and type errors.\n\n### Provider abstraction\n\nAll three SCM providers implement `ScmProvider` from `providers/base.js`. The contract is:\n- **Normalized return types** — all methods return `NormalIssue`, `NormalMR`, `NormalPipeline`, etc., regardless of provider\n- **Instance-scoped** — each provider is instantiated with a repo string; no global state\n- **`supportsRebase`** — providers that don't support server-side rebase return `false`; the UI and API layer check this before showing the rebase button\n\n---\n\n## Programmatic usage\n\nMount the Forge Express router or use the core classes directly:\n\n```js\nimport forgeRouter from \"@ipul-labs/forge\"; // Express router\nimport { ForgeAgent } from \"@ipul-labs/forge/agent\"; // Core pipeline class\nimport { createProvider } from \"@ipul-labs/forge/providers\"; // SCM factory\n```\n\n```js\nconst agent = new ForgeAgent({ project: \"group/repo\" });\nconst result = await agent.analyzeIssue(42, (event) => console.log(event));\nconst { branchName, mr } = await agent.applyFix(result);\n```\n\n---\n\n## License\n\nMIT\n"
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ const fs = require("fs");
3
+ const path = require("path");
4
+
5
+ const root = path.resolve(__dirname, "..");
6
+ const pkgPath = path.join(root, "package.json");
7
+ const readmePath = path.join(root, "README.md");
8
+
9
+ if (!fs.existsSync(readmePath)) process.exit(0);
10
+
11
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
12
+ pkg.readme = fs.readFileSync(readmePath, "utf8");
13
+ fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
@@ -0,0 +1,134 @@
1
+ #!/usr/bin/env bash
2
+ # ──────────────────────────────────────────────────────────────────────────────
3
+ # Local dry-run of the same manifests + commands the *-rollout CI jobs execute.
4
+ # Catches manifest bugs, missing env vars, image-pull problems, and rollout
5
+ # logic errors BEFORE burning another CI cycle. Uses your local kubeconfig
6
+ # (admin creds against k3s), so it does NOT test the agent SA's RBAC — for
7
+ # that, the actual CI run is still the source of truth.
8
+ #
9
+ # ./scripts/local-rollout.sh [test|prep|prod] [image-tag]
10
+ #
11
+ # Defaults: env=test, image-tag=<current deployment's tag OR "latest">
12
+ #
13
+ # Exits non-zero on the first failure with a clear message.
14
+ # ──────────────────────────────────────────────────────────────────────────────
15
+
16
+ set -euo pipefail
17
+
18
+ ENV=${1:-test}
19
+ IMAGE_TAG=${2:-}
20
+
21
+ case "$ENV" in
22
+ test) NS=test; DEPLOY=forge-test; MANIFEST_DIR=manifests/test/forge-test ;;
23
+ prep) NS=prep; DEPLOY=forge-prep; MANIFEST_DIR=manifests/prep/forge-prep ;;
24
+ prod) NS=prod; DEPLOY=forge; MANIFEST_DIR=manifests/prod/forge ;;
25
+ *) echo "Usage: $0 [test|prep|prod] [image-tag]"; exit 2 ;;
26
+ esac
27
+
28
+ # All envs pull from the same consolidated image repo. Per-env differences
29
+ # live in the manifests, not in the image.
30
+ IMAGE_REPO=iplayulisten/forge
31
+
32
+ # ─── Helpers ──────────────────────────────────────────────────────────────────
33
+
34
+ c_step() { printf '\n\033[1;34m── %s ──\033[0m\n' "$*"; }
35
+ c_ok() { printf '\033[1;32m✓\033[0m %s\n' "$*"; }
36
+ c_warn() { printf '\033[1;33m⚠\033[0m %s\n' "$*"; }
37
+ c_fail() { printf '\033[1;31m✗\033[0m %s\n' "$*"; exit 1; }
38
+
39
+ require() { command -v "$1" >/dev/null 2>&1 || c_fail "missing required binary: $1"; }
40
+
41
+ # ─── Preflight ────────────────────────────────────────────────────────────────
42
+
43
+ c_step "Preflight"
44
+ require kubectl
45
+ require openssl
46
+
47
+ CTX=$(kubectl config current-context 2>/dev/null || true)
48
+ [ -n "$CTX" ] || c_fail "no current kubectl context — set one with 'kubectl config use-context <name>'"
49
+ c_ok "kubectl context: $CTX"
50
+
51
+ if ! kubectl get ns "$NS" >/dev/null 2>&1; then
52
+ c_warn "namespace '$NS' doesn't exist — creating it"
53
+ kubectl create namespace "$NS"
54
+ c_ok "namespace '$NS' created"
55
+ else
56
+ c_ok "namespace '$NS' exists"
57
+ fi
58
+
59
+ [ -d "$MANIFEST_DIR" ] || c_fail "manifest dir not found: $MANIFEST_DIR"
60
+ c_ok "manifest dir: $MANIFEST_DIR"
61
+
62
+ # ─── Secret creation (mirrors CI) ─────────────────────────────────────────────
63
+
64
+ c_step "Secret: forge-secret"
65
+ : "${FORGE_TOKEN:=}"
66
+ : "${ANTHROPIC_API_KEY:=}"
67
+ : "${GITLAB_TOKEN:=}"
68
+
69
+ if [ -z "$FORGE_TOKEN" ]; then
70
+ c_warn "FORGE_TOKEN unset — generating a throwaway for this run"
71
+ FORGE_TOKEN=$(openssl rand -hex 32)
72
+ fi
73
+ [ -n "$GITLAB_TOKEN" ] || c_warn "GITLAB_TOKEN unset (forge backend needs this at runtime — ok for manifest test)"
74
+ [ -n "$ANTHROPIC_API_KEY" ] || c_warn "ANTHROPIC_API_KEY unset (optional, only needed for quota probe)"
75
+
76
+ kubectl create secret generic forge-secret \
77
+ --from-literal=FORGE_TOKEN="$FORGE_TOKEN" \
78
+ --from-literal=ANTHROPIC_API_KEY="$ANTHROPIC_API_KEY" \
79
+ --from-literal=GITLAB_TOKEN="$GITLAB_TOKEN" \
80
+ -n "$NS" --dry-run=client -o yaml | kubectl apply -f -
81
+ c_ok "forge-secret applied"
82
+
83
+ # ─── Apply manifests in CI order ──────────────────────────────────────────────
84
+
85
+ for f in config-map.yaml service.yaml deployment.yaml; do
86
+ path="$MANIFEST_DIR/$f"
87
+ [ -f "$path" ] || c_fail "missing manifest: $path"
88
+ c_step "Applying $f"
89
+ kubectl apply -f "$path"
90
+ c_ok "$f applied"
91
+ done
92
+
93
+ # ─── Image tag ────────────────────────────────────────────────────────────────
94
+
95
+ if [ -z "$IMAGE_TAG" ]; then
96
+ CURRENT_IMAGE=$(kubectl get deploy/"$DEPLOY" -n "$NS" -o jsonpath='{.spec.template.spec.containers[0].image}' 2>/dev/null || true)
97
+ if [ -n "$CURRENT_IMAGE" ] && [ "$CURRENT_IMAGE" != "*__VERSION__*" ] && [[ "$CURRENT_IMAGE" != *__VERSION__* ]]; then
98
+ IMAGE_TAG=${CURRENT_IMAGE##*:}
99
+ c_ok "reusing current deployment image tag: $IMAGE_TAG"
100
+ else
101
+ IMAGE_TAG=latest
102
+ c_warn "no usable tag in current deployment — falling back to '$IMAGE_TAG' (may fail to pull)"
103
+ fi
104
+ fi
105
+
106
+ c_step "kubectl set image → ${IMAGE_REPO}:${IMAGE_TAG}"
107
+ kubectl set image deployment/"$DEPLOY" -n "$NS" "${DEPLOY}=${IMAGE_REPO}:${IMAGE_TAG}"
108
+ c_ok "image set"
109
+
110
+ # ─── Rollout ──────────────────────────────────────────────────────────────────
111
+
112
+ c_step "Rollout status (120s timeout)"
113
+ if kubectl rollout status deployment/"$DEPLOY" -n "$NS" --timeout=120s; then
114
+ c_ok "rollout succeeded"
115
+ else
116
+ c_warn "rollout did not finish in 120s — dumping pod state to help diagnose"
117
+ kubectl get pods -n "$NS" -l app="$DEPLOY" -o wide || true
118
+ kubectl describe deployment/"$DEPLOY" -n "$NS" | sed -n '/Events:/,$p' || true
119
+ kubectl get events -n "$NS" --sort-by=.lastTimestamp | tail -20 || true
120
+ exit 1
121
+ fi
122
+
123
+ # ─── Summary ──────────────────────────────────────────────────────────────────
124
+
125
+ c_step "Summary"
126
+ kubectl get pods,svc,deploy -n "$NS" -l app="$DEPLOY"
127
+ c_ok "local rollout for '$ENV' passed"
128
+ echo
129
+ echo "Next: push CI. If CI fails where this didn't, it's agent SA RBAC."
130
+ echo "To tear down what this script created:"
131
+ echo " kubectl delete -f $MANIFEST_DIR/deployment.yaml -n $NS"
132
+ echo " kubectl delete -f $MANIFEST_DIR/service.yaml -n $NS"
133
+ echo " kubectl delete -f $MANIFEST_DIR/config-map.yaml -n $NS"
134
+ echo " kubectl delete secret forge-secret -n $NS"