#!/usr/bin/env bash # # install.sh - Cross-tool installer for the Cloud FinOps Skill & MCP. # #>>USAGE # Usage: # ./install.sh Auto-detect tools in cwd / $HOME and install for each # ./install.sh --tool Install for one specific tool # ./install.sh --tool all Install for every supported tool # ./install.sh --list List supported tools # ./install.sh --dry-run Print what would happen, no writes # ./install.sh --user Install at user-level paths where supported (Claude Code) # ./install.sh --grouped ChatGPT only: produce a grouped build that bundles # the same content by domain into a handful of files # instead of one file per reference. Easier to upload. # ./install.sh --inline Single-file targets (cursor, windsurf, codex, # aider): inline the entire reference library # instead of emitting a routing file. Produces # a ~1MB artefact - only useful without the MCP # server and without a local checkout. # ./install.sh --dest Override the project / target directory # ./install.sh --help Show this help # # Tools: claude-code, claude-projects, cursor, windsurf, chatgpt, gemini, # gemini-cli, codex, aider, copilot, kiro, mcp # # The "mcp" target is special: it does NOT install Python packages. It prints # the install hint (`pip install cloud-finops-mcp`) plus per-client config # snippets so you can wire any MCP-aware tool (Claude Code, Cursor, Codex, # Windsurf, Cline, etc.) at the cloud-finops MCP server. #<", "copied ->") and some # carry counts computed during the build, so under --dry-run they would claim # work that did not happen. Suppress them: do_write / do_copy_dir already print # a "DRY-RUN would write/copy: " line carrying the same path. ok() { [[ -n "${DRY_RUN:-}" ]] && return 0 printf "${C_GREEN}[OK]${C_RESET} %s\n" "$*" } warn() { printf "${C_YELLOW}[!!]${C_RESET} %s\n" "$*"; } err() { printf "${C_RED}[ERR]${C_RESET} %s\n" "$*" >&2; } info() { printf "${C_BLUE}[..]${C_RESET} %s\n" "$*"; } dim() { printf "${C_DIM}%s${C_RESET}\n" "$*"; } # ---- constants ---- REPO_URL="https://github.com/OptimNow/cloud-finops-skills.git" SKILL_NAME="cloud-finops" # Provenance line emitted into single-file artefacts that land on a filename # other tools also claim (AGENTS.md, CONVENTIONS.md). Lets a re-run recognise # its own output and overwrite in place instead of forking to a suffixed name. PROVENANCE="" ALL_TOOLS=(claude-code claude-projects cursor windsurf chatgpt gemini gemini-cli codex aider copilot kiro mcp) # The named waste patterns the playbook library covers, as one comma-separated # list. Emitted verbatim into the "Named waste pattern" routing row of BOTH # ChatGPT instruction variants - the per-reference one (routing to # playbook-.md) and the grouped one (routing to a section of # playbooks.md). It was ~330 words duplicated byte-for-byte between the two # builders, which meant every new playbook had to be added twice and an # omission in one variant was invisible: the grouped build simply stopped # routing to a pattern the default build still knew about. # # The routing rows live inside quoted heredocs (so the backticks and # placeholders around them stay literal), so each builder breaks its heredoc # for one printf rather than switching to an unquoted heredoc. NAMED_WASTE_PATTERNS="zombie NAT, snapshot sprawl, idle ELB, Kinesis stream with no consumers, cross-AZ egress, oversized RDS, orphan EBS, orphan Azure disks, App Service overprovisioning, Log Analytics ingestion sprawl, idle Azure SQL, idle GKE Autopilot, orphan Persistent Disks, Cloud Functions cold starts, schedule blindness, untagged spend drift, idle SageMaker endpoint, always-on SageMaker notebook, SageMaker endpoint sprawl / MME consolidation, oversized GPU instance, multi-GPU underutilized, MIG candidate, GPU for CPU-bound workload, outdated GPU generation, agent-loop flat-line burn, coding-agent token waste, expiring commitment without a renewal decision, unused Azure reservation, GCP CUD mismatch, S3 incomplete multipart uploads, S3 noncurrent version sprawl, S3 cold data in Standard, NAT-to-gateway-endpoint substitution, idle Azure VM (stopped not deallocated), orphaned Azure public IPs and NICs, Azure snapshot sprawl, gp2-to-gp3 migration, Graviton candidate, Azure Blob version and soft-delete sprawl, Azure Blob cold data in Hot, GCS soft-delete and noncurrent version sprawl, GCS cold data in Standard, GCP Cloud Logging ingestion sprawl" # Emit the "Named waste pattern" routing row. $1 is the knowledge-file column, # which is the only thing that differs between the two variants. emit_named_pattern_row() { printf '| Named waste pattern (%s) | %s |\n' "$NAMED_WASTE_PATTERNS" "$1" } # ---- state ---- SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd || pwd)" SRC_DIR="" # Where resolve_source clones the repo when there is no local checkout, cleaned # up on exit. Named CLONE_TMP, not TMPDIR: TMPDIR is a standard exported # variable that every child process (git, mktemp, rsync, python) reads to find # the system temp directory, and this script used to overwrite it with "" and # then with its own clone path. Renaming leaves the caller's TMPDIR alone - and # lets the `mktemp -d` below honour it, which it could not while we were the # ones setting it. CLONE_TMP="" TOOL="" DRY_RUN="" USER_LEVEL="" DEST_OVERRIDE="" GROUPED="" INLINE="" cleanup() { [[ -n "$CLONE_TMP" ]] && rm -rf "$CLONE_TMP" 2>/dev/null || true; } trap cleanup EXIT # ---- helpers ---- # Print the help block delimited by the #>>USAGE / #<>USAGE$/{f=1; next} /^#</dev/null 2>&1; then err "git not found and no local source. Install git or run from a clone of the repo." exit 1 fi CLONE_TMP=$(mktemp -d 2>/dev/null || mktemp -d -t 'finops-skill') git clone --depth 1 --quiet "$REPO_URL" "$CLONE_TMP/cloud-finops-skills" SRC_DIR="$CLONE_TMP/cloud-finops-skills" fi } # Strip the YAML frontmatter (between the first two --- lines) from a markdown file. # # `sub(/\r$/,"")` on every line before matching, the same handling # scripts/fcp-coverage.sh and scripts/playbook-coverage.sh already use. On a # CRLF checkout - WSL running against a Windows clone with core.autocrlf=true, # a combination this script explicitly supports - the fence line is `---\r`, # which `/^---$/` never matches. The frontmatter delimiter is then never seen, # f stays 0, nothing is printed, and every generated artefact silently loses # the SKILL.md body. (The pre-fix behaviour was worse in the emit paths below, # where the whole YAML block leaked into the artefact instead.) strip_frontmatter() { awk 'BEGIN{f=0} {sub(/\r$/,"")} /^---$/{f++; if(f<=2) next} f>=2{print}' "$1" } # Concatenated body: SKILL.md (no frontmatter) + every reference file + # every playbook. SKILL.md routes named waste patterns to playbooks/.md, # so the playbooks must be inlined too - otherwise the routing contract points # the model at files that are not present in the installed artefact. write_concat_body() { strip_frontmatter "$SRC_DIR/plugins/cloud-finops/skills/cloud-finops/SKILL.md" echo echo "---" echo echo "## Reference files" echo for ref in "$SRC_DIR/plugins/cloud-finops/skills/cloud-finops/references"/*.md; do echo "### $(basename "$ref" .md)" echo cat "$ref" echo echo "---" echo done if [[ -d "$SRC_DIR/plugins/cloud-finops/skills/cloud-finops/playbooks" ]]; then echo echo "## Playbooks" echo for pb in "$SRC_DIR/plugins/cloud-finops/skills/cloud-finops/playbooks"/*.md; do local pb_name pb_name=$(basename "$pb") # Skip the directory's own README - it documents the format / # convention for human contributors, not a runbook the model # should retrieve as a pattern. [[ "$pb_name" == "README.md" ]] && continue echo "### playbooks/$pb_name" echo cat "$pb" echo echo "---" echo done fi } # Routing body: SKILL.md (the router) + a one-line index of every reference and # playbook + instructions for fetching a body on demand. # # This is the default for the single-file targets (cursor, windsurf, codex, # aider). The alternative - inlining the whole library, which write_concat_body # does - produces a ~1MB artefact (~250K tokens) that overflows or dominates # any context window, and Windsurf's per-rule character limit is orders of # magnitude below it. The library was a fraction of its current size when that # approach was chosen. `--inline` restores it for anyone who wants it. # # The routing contract only works if the model can actually reach the bodies, # so the header states both retrieval paths explicitly. # Emit "- `` - " for every reference, taking the description # from the file's line-3 blockquote. # # This loop used to exist twice - here and in build_copilot_instructions - with # two undocumented differences: the copilot copy truncated at 180 characters # instead of 220 and kept the `.md` suffix on the label. Neither difference was # deliberate, so the two call sites are now one and the longer, suffix-free form # won (it matches how references are named everywhere else in the repo). emit_reference_index() { local ref desc name for ref in "$SRC_DIR/plugins/cloud-finops/skills/cloud-finops/references"/*.md; do name=$(basename "$ref" .md) # sub(/\r$/,"") for CRLF checkouts: without it the description carries a # trailing carriage return into the middle of the generated index line. desc=$(awk '{sub(/\r$/,"")} /^>/{sub(/^> ?/,""); print; exit}' "$ref" | head -c 220) echo "- \`$name\` - $desc" done } write_routing_body() { strip_frontmatter "$SRC_DIR/plugins/cloud-finops/skills/cloud-finops/SKILL.md" cat <<'EOF' --- ## Retrieving a reference or playbook The routing tables above name files that are **not inlined in this artefact**. Fetch a body one of two ways: 1. **cloud-finops MCP server** (recommended). `pip install cloud-finops-mcp`, then wire it into this tool's MCP config. Tools: - `get_reference(name)` / `list_references()` / `find_references(domain=, capability=, phase=, persona=, maturity=)` - `get_playbook(name)` / `list_playbooks()` / `find_playbooks(scope=, service=, waste_category=, confidence=)` 2. **Local checkout.** If this project has the skill installed on disk, read `plugins/cloud-finops/skills/cloud-finops/references/.md` or `plugins/cloud-finops/skills/cloud-finops/playbooks/.md` directly. If neither is available, say so rather than answering from memory - the whole point of this skill is that billing mechanics come from the reference files, not from model recall. --- ## Reference index EOF emit_reference_index if [[ -d "$SRC_DIR/plugins/cloud-finops/skills/cloud-finops/playbooks" ]]; then cat <<'EOF' ## Playbook index Named-pattern runbooks. Format: slug - scope / waste category / confidence. EOF local pb slug scope cat conf for pb in "$SRC_DIR/plugins/cloud-finops/skills/cloud-finops/playbooks"/*.md; do [[ "$(basename "$pb")" == "README.md" ]] && continue slug=$(basename "$pb" .md) # Same CRLF handling as above: a trailing carriage return would otherwise # ride along in every facet value and land mid-line in the generated index. scope=$(awk -F': *' '{sub(/\r$/,"")} /^scope:/{print $2; exit}' "$pb") cat=$(awk -F': *' '{sub(/\r$/,"")} /^waste_category:/{print $2; exit}' "$pb") conf=$(awk -F': *' '{sub(/\r$/,"")} /^confidence:/{print $2; exit}' "$pb") echo "- \`$slug\` - ${scope:-?} / ${cat:-?} / ${conf:-?}" done fi echo } # Emit either the routing body (default) or the full inlined library # (--inline). Single-file targets call this rather than either builder. write_body() { if [[ -n "$INLINE" ]]; then write_concat_body else write_routing_body fi } # Explain to the user which shape they just got and how the model reaches the # reference bodies from it. routing_hint() { [[ -n "$DRY_RUN" ]] && return 0 if [[ -n "$INLINE" ]]; then dim " --inline: the full reference library is embedded (~1MB). Expect this to" dim " dominate or overflow the tool's context window." else dim " This is a routing file: SKILL.md plus an index, not the full library." dim " Install the MCP server so the model can fetch bodies on demand:" dim " pip install cloud-finops-mcp (then: ./install.sh --tool mcp for config)" dim " Or keep a local checkout - the routing file explains both paths." fi } # True when an existing file carries our provenance line, i.e. a previous run # of this installer wrote it and overwriting in place is safe. Only the head of # the file is checked - the marker is emitted in the header block. is_ours() { head -n 20 "$1" 2>/dev/null | grep -qF "cloud-finops-skill: generated by install.sh" } # Idempotent file write with dry-run support do_write() { local target="$1" local content_fn="$2" if [[ -n "$DRY_RUN" ]]; then info "DRY-RUN would write: $target" return fi mkdir -p "$(dirname "$target")" $content_fn > "$target" } # Idempotent directory copy with dry-run support. # Excludes local-only artefacts that may exist in the maintainer's worktree: # .claude/ - local Claude Code settings # .backups/ - pipeline backups (plugins/cloud-finops/skills/cloud-finops/references/.backups/) # .git/ - if SRC happens to be a git repo do_copy_dir() { local src="$1" dest="$2" if [[ -n "$DRY_RUN" ]]; then info "DRY-RUN would copy: $src -> $dest (excluding .claude, .backups, .git)" return fi mkdir -p "$(dirname "$dest")" # Stage into a sibling temp dir and swap, so an interrupt mid-copy cannot # leave the user with their previous install deleted and nothing in its place. local staging="$dest.tmp.$$" rm -rf "$staging" if command -v rsync >/dev/null 2>&1; then mkdir -p "$staging" rsync -a --exclude='.claude' --exclude='.backups' --exclude='.git' "$src/" "$staging/" else cp -r "$src" "$staging" rm -rf "$staging/.claude" "$staging/.git" 2>/dev/null || true find "$staging" -type d -name '.backups' -exec rm -rf {} + 2>/dev/null || true fi rm -rf "$dest" mv "$staging" "$dest" } # ---- detection ---- detect_claude_code() { [[ -d ".claude" || -d "$HOME/.claude" ]]; } detect_claude_projects() { return 1; } # web-only, never auto-detected detect_cursor() { command -v cursor >/dev/null 2>&1 || [[ -d ".cursor" || -d "$HOME/.cursor" ]]; } detect_windsurf() { command -v windsurf >/dev/null 2>&1 || [[ -d ".windsurf" || -d "$HOME/.codeium" ]]; } detect_chatgpt() { return 1; } # web-only detect_gemini() { return 1; } # web-only detect_gemini_cli() { command -v gemini >/dev/null 2>&1 || [[ -d "$HOME/.gemini" ]]; } detect_codex() { command -v codex >/dev/null 2>&1 || [[ -d ".codex" || -d "$HOME/.codex" ]]; } # Auto-detect writes files into the user's project, so the signal has to be # specific to the tool. CONVENTIONS.md is a convention several tools use, and # `code` on PATH says the user has VS Code - not that they want a Copilot # instructions file written into this repo. Both were dropped for that reason # (as was the earlier .github/ heuristic, which fired on every repo with # workflows or issue templates). Either target is still reachable explicitly # via --tool aider / --tool copilot. detect_aider() { command -v aider >/dev/null 2>&1; } detect_copilot() { [[ -f ".github/copilot-instructions.md" ]]; } detect_kiro() { command -v kiro >/dev/null 2>&1 || [[ -d ".kiro" ]]; } # MCP target is always opt-in via --tool mcp; auto-detection is intentionally off. detect_mcp() { return 1; } is_detected() { case "$1" in claude-code) detect_claude_code ;; claude-projects) detect_claude_projects ;; cursor) detect_cursor ;; windsurf) detect_windsurf ;; chatgpt) detect_chatgpt ;; gemini) detect_gemini ;; gemini-cli) detect_gemini_cli ;; codex) detect_codex ;; aider) detect_aider ;; copilot) detect_copilot ;; kiro) detect_kiro ;; mcp) detect_mcp ;; *) return 1 ;; esac } # ---- per-tool installers ---- install_claude_code() { local target if [[ -n "$DEST_OVERRIDE" ]]; then target="$DEST_OVERRIDE/$SKILL_NAME" elif [[ -n "$USER_LEVEL" ]]; then target="$HOME/.claude/skills/$SKILL_NAME" else target="$PWD/.claude/skills/$SKILL_NAME" fi do_copy_dir "$SRC_DIR/plugins/cloud-finops/skills/cloud-finops" "$target" ok "Claude Code: skill copied -> $target" dim " Restart Claude Code or run /reload-plugins to pick up changes." } install_claude_projects() { local outdir="${DEST_OVERRIDE:-$PWD}/dist/claude-projects" if [[ -n "$DRY_RUN" ]]; then info "DRY-RUN would build: $outdir/cloud-finops.zip" return fi mkdir -p "$outdir" if command -v python3 >/dev/null 2>&1; then python3 - "$SRC_DIR/plugins/cloud-finops/skills/cloud-finops" "$outdir/cloud-finops.zip" <<'PYEOF' import os, sys, zipfile src_dir, out_zip = sys.argv[1], sys.argv[2] src_root = os.path.dirname(os.path.abspath(src_dir)) EXCLUDE = {".claude", ".backups", ".git"} with zipfile.ZipFile(out_zip, 'w', zipfile.ZIP_DEFLATED) as z: for root, dirs, files in os.walk(src_dir): dirs[:] = [d for d in dirs if d not in EXCLUDE] for f in files: full = os.path.join(root, f) arcname = os.path.relpath(full, src_root).replace(os.sep, '/') z.write(full, arcname) PYEOF elif command -v zip >/dev/null 2>&1; then (cd "$SRC_DIR/skills" && zip -r -q "$outdir/cloud-finops.zip" cloud-finops \ -x 'cloud-finops/.claude/*' \ -x 'cloud-finops/**/.backups/*' \ -x 'cloud-finops/.git/*') else err "Neither python3 nor zip found. Cannot build claude-projects zip." return 1 fi ok "Claude Projects: zip built -> $outdir/cloud-finops.zip" dim " Manual upload: claude.ai or Claude Desktop -> Settings -> Skills -> Upload zip." } install_cursor() { local target="${DEST_OVERRIDE:-$PWD}/.cursor/rules/cloud-finops.mdc" do_write "$target" build_cursor_rule ok "Cursor: rule written -> $target" dim " Cursor auto-loads .cursor/rules/. Trigger by asking a FinOps question in chat." routing_hint } build_cursor_rule() { cat <<'EOF' --- description: Expert FinOps guidance for cloud, AI, SaaS, and data-platform spend (multi-provider, model-agnostic). Use for cost questions on AWS, Azure, GCP, Anthropic, open-weight vendor APIs (DeepSeek, Qwen, Kimi, GLM), Bedrock, Vertex AI, Azure OpenAI, Databricks, Microsoft Fabric, Snowflake, OCI, AI coding tools, self-hosted vs managed AI inference, agentic FinOps, GenAI capacity planning, AI value management, GreenOps, FinOps Framework, SaaS asset management, ITAM, cloud contract negotiation (EDP / Private Pricing, MACC, Google Cloud commitments), anomaly management, allocation and showback, chargeback, onboarding workloads, Kubernetes FinOps, waste detection, KPIs and benchmarking, forecasting, FinOps practice operations (operating model, RACI, governance, ITFM), on-premises and hybrid FinOps, FOCUS multi-cloud cost data normalisation. globs: - "**/*" alwaysApply: false --- EOF write_body } install_windsurf() { local target="${DEST_OVERRIDE:-$PWD}/.windsurf/rules/cloud-finops.md" do_write "$target" build_windsurf_rule ok "Windsurf: rule written -> $target" routing_hint } build_windsurf_rule() { cat <<'EOF' --- trigger: model_decision description: Expert FinOps guidance for cloud, AI, SaaS, and data-platform spend (multi-provider, model-agnostic). --- EOF write_body } install_chatgpt() { local outdir="${DEST_OVERRIDE:-$PWD}/dist/chatgpt" local instructions_path="$outdir/instructions.md" local knowledge_dir="$outdir/knowledge" if [[ -n "$DRY_RUN" ]]; then info "DRY-RUN would write: $instructions_path" info "DRY-RUN would write: $knowledge_dir/*.md" return fi # Wipe any previous build so renamed/removed references don't linger rm -rf "$knowledge_dir" mkdir -p "$knowledge_dir" if [[ -n "$GROUPED" ]]; then # Grouped build emits a routing contract that points at the grouped # filenames (aws.md, azure.md, ai.md, ...) rather than per-reference names. build_grouped_instructions > "$instructions_path" else build_chatgpt_instructions > "$instructions_path" fi local size size=$(wc -c < "$instructions_path") if [[ -n "$GROUPED" ]]; then # Grouped build: same domain bundling as Gemini. Produces a handful of # thematic knowledge files rather than one per reference - well under any # historical ChatGPT Custom GPT cap and easier to upload reliably. Routing # contract above already points at the grouped filenames. build_gemini_grouped_knowledge "$knowledge_dir" else # Per-reference build: one knowledge file per reference plus one per # playbook, methodology merged into finops-for-ai.md. May exceed ChatGPT's # historical file cap - --grouped is the fallback. local methodology="$SRC_DIR/plugins/cloud-finops/skills/cloud-finops/references/optimnow-methodology.md" for ref in "$SRC_DIR/plugins/cloud-finops/skills/cloud-finops/references"/*.md; do local name name=$(basename "$ref") if [[ "$name" == "optimnow-methodology.md" ]]; then continue fi if [[ "$name" == "finops-for-ai.md" ]]; then { cat "$ref" echo echo "---" echo echo "## Reasoning Methodology Appendix" echo [[ -f "$methodology" ]] && cat "$methodology" } > "$knowledge_dir/$name" else cp "$ref" "$knowledge_dir/$name" fi done # Playbooks: SKILL.md routes named-pattern queries to playbooks/.md, # so each playbook must be uploadable as a knowledge file too. Prefix # the filename so they group together in the GPT Knowledge UI and don't # collide with reference filenames. if [[ -d "$SRC_DIR/plugins/cloud-finops/skills/cloud-finops/playbooks" ]]; then for pb in "$SRC_DIR/plugins/cloud-finops/skills/cloud-finops/playbooks"/*.md; do local pb_name pb_name=$(basename "$pb") [[ "$pb_name" == "README.md" ]] && continue cp "$pb" "$knowledge_dir/playbook-$pb_name" done fi fi local file_count file_count=$(find "$knowledge_dir" -maxdepth 1 -name "*.md" | wc -l | tr -d ' ') ok "ChatGPT: instructions ($size chars) -> $instructions_path" ok "ChatGPT: $file_count knowledge files -> $knowledge_dir/" # Warn before the ceiling, not only after it. Every routing-table row added to # build_inline_instructions grows this file, and the build lands close enough to # 8000 that a single new row can breach it. Same early-warning shape as # scripts/check-skill-description.sh. if [[ $size -gt 8000 ]]; then warn "Instructions exceed ChatGPT's ~8000 char limit ($size chars). Manual trim needed." elif [[ $size -gt 7400 ]]; then warn "Instructions are $size of ~8000 chars. Little headroom - tighten a routing row before adding another." fi if [[ $file_count -gt 20 ]]; then warn "ChatGPT historically capped Custom GPT Knowledge at 20 files. Current build is $file_count files." dim " If your upload is rejected, re-run with --grouped to produce a smaller" dim " bundled build (same content, fewer files): ./install.sh --tool chatgpt --grouped" fi dim " Manual upload steps:" dim " 1. Open https://chatgpt.com/gpts/editor" dim " 2. Paste $instructions_path into the Instructions field" dim " 3. Upload all files from $knowledge_dir/ to Knowledge" if [[ -z "$GROUPED" ]]; then dim " 4. Note: methodology is merged into finops-for-ai.md to keep file count down." dim " Playbook files are prefixed playbook-* so they sort together in the GPT UI." else dim " 4. Grouped mode: thematic files (aws, azure, gcp, ai, data-platforms," dim " oci, cross-cutting, finops-discipline, playbooks, methodology)" fi } # The tail of both ChatGPT instruction variants - reasoning sequence, price # figures, response format, maturity awareness, source - was duplicated verbatim # across build_chatgpt_instructions and build_grouped_instructions. It differs in # exactly two places: where the methodology lens lives, and whether the knowledge # files are called "domain" or "grouped". Every doctrine edit therefore had to be # made twice, and an edit applied to only one variant drifted silently. # # $1 - where the methodology lens lives, as it should read in prose # $2 - the adjective for the knowledge files ("domain" or "grouped") # # Note the escaped \$X below: this heredoc is unquoted so $1/$2 expand, which # means the literal "$X per 1M input tokens" needs protecting. emit_instructions_tail() { local methodology_ref="$1" local file_noun="$2" cat <, )". A figure with no date is not usable in a client deliverable. - For a current figure, refer the user to https://optimtoken.optimnow.io rather than quoting from memory. - Never interpolate a missing price from a neighbouring model, a previous generation, or another region. If the figure is not available, say so. ## Response format Structure substantive answers with these headers: - **Context** - what the user told you, what assumptions you're making - **Recommendation** - the actionable advice - **Metrics and signals** - what to measure or watch - **Business impact** - how this connects to outcomes (cost saved, risk reduced, capability unlocked) For brief factual questions, skip the structure. Use it for advisory or strategy questions. ## Maturity awareness Always assess maturity before recommending solutions. A Crawl organisation (cost allocation <50%) needs visibility before optimisation. Recommending commitment discounts to an org with poor allocation creates committed waste. ## Source Cloud FinOps Skill by OptimNow (https://optimnow.io). Licensed CC BY-SA 4.0. Source: https://github.com/OptimNow/cloud-finops-skills EOF } build_chatgpt_instructions() { cat <<'EOF' # Cloud FinOps Expert Assistant You are an expert FinOps practitioner. Help users understand and optimise spend on cloud (AWS / Azure / GCP / OCI), AI platforms, data platforms (Databricks, Fabric, Snowflake), AI coding tools, SaaS, on-premises and hybrid estates, and cross-cutting concerns (tagging, FinOps Framework, GreenOps, ITAM). Your knowledge files contain accurate, current billing mechanics and optimisation patterns updated weekly. Always retrieve relevant knowledge files before answering - do not rely on general training data for billing specifics. ## Domain routing Use these knowledge files for the following query types: | Query topic | Knowledge file | |---|---| | AWS rightsizing, SageMaker, RDS, CloudFront, S3 Files | finops-aws.md | | AWS CUR, exports, allocation, SCPs, Budgets, invoices | finops-aws-billing.md | | AWS Savings Plans, Reserved Instances, Spot, commitment strategy, EDP | finops-aws-commitments.md | | AWS optimisation pattern catalogue | finops-aws-patterns.md | | AWS Bedrock model pricing, Application Inference Profiles, prompt caching | finops-bedrock.md | | Azure rightsizing, AKS, Log Analytics, storage, networking | finops-azure.md | | Azure exports, allocation, Policy, budgets, MCA | finops-azure-billing.md | | Azure Reservations, Savings Plans, AHB, MACC, commitment strategy | finops-azure-commitments.md | | Azure optimisation pattern catalogue | finops-azure-patterns.md | | Azure OpenAI / Foundry PTUs | finops-azure-openai.md | | Anthropic Claude billing, Fast mode, prompt caching, long-context | finops-anthropic.md | | GCP cost management, BigQuery export, CUDs, SUDs, Spot, Carbon Footprint | finops-gcp.md | | Vertex AI / Gemini pricing, Provisioned Throughput, context caching, Flexible Savings Plans | finops-vertexai.md | | AI cost management, LLM economics, agentic patterns, ROI, methodology lens | finops-for-ai.md | | Agentic FinOps, agent cost anatomy, cost per completed task, agent payments (x402/MPP) | finops-agentic.md | | AI investment governance, stage gates, AI business case, value quantification | finops-ai-value-management.md | | GenAI capacity planning, provisioned vs shared, spillover | finops-genai-capacity.md | | Self-hosted vs managed inference, vLLM, GPU rental | finops-ai-self-hosted-vs-managed.md | | Open-weight vendor APIs (DeepSeek, Qwen, Kimi, GLM), time-based pricing, licensing | finops-open-weight-vendors.md | | AI coding tools (Cursor, Copilot, Claude Code, Codex, Windsurf) | finops-ai-dev-tools.md | | Databricks (system.billing.usage, DBCU, allocation, Photon) | finops-databricks.md | | Microsoft Fabric (F-SKUs, CU smoothing, pause/resume, governance trap) | finops-fabric.md | | Snowflake (query attribution, Budgets, Cortex, resource monitors) | finops-snowflake.md | | OCI (Cost Reports, FOCUS, cost-tracking tags, Universal Credits) | finops-oci.md | | FinOps Framework 2026 (4 domains, 22 capabilities) | finops-framework.md | | Tagging strategy, naming conventions, IaC enforcement | finops-tagging.md | | SaaS management, licence optimisation, shadow IT | finops-sam.md | | ITAM, BYOL, marketplace governance | finops-itam.md | | Cloud contracts: EDP/PPA, MACC/ACD, Google commitment, term sheets | finops-cloud-contracts.md | | GreenOps, cloud carbon, sustainability | greenops-cloud-carbon.md | | Cost anomaly management, masked anomalies, threshold tuning | finops-anomaly-management.md | | FinOps KPIs, unit economics, benchmarking, executive reporting | finops-kpis-benchmarking.md | | Forecasting, accuracy and drift, driver-based and AI forecasts | finops-forecasting.md | | Allocation methodology and showback, EffectiveCost vs BilledCost, shared services | finops-allocation-showback.md | | Chargeback, soft-to-hard maturity, Finance prerequisites (ERP, tax, SOX) | finops-chargeback.md | | FinOps operating model, RACI, governance forums, ITFM / TBM handoffs | finops-practice-operations.md | | Onboarding workloads, intake gate, double-bubble cost, M&A, divestiture | finops-onboarding-workloads.md | | Kubernetes FinOps (EKS / GKE / AKS), OpenCost / Kubecost, Karpenter | finops-kubernetes.md | | On-prem and hybrid: internal bill, Outposts / Azure Local / Arc / VMware, exit fees | finops-on-prem-hybrid.md | | FOCUS normalisation, versions and export differences, ingestion pipeline | finops-focus.md | | Waste taxonomy (eight categories), two-signal classification, egress waste, WasteLine | finops-waste-detection-playbooks.md | EOF # A representative list, not the full one: the playbook files are named after # their pattern, so retrieval matches on the file name. The full list stays in # NAMED_WASTE_PATTERNS for the grouped build, where every playbook sits in one # playbooks.md file and the row is the only index. Extend this list only for a # new pattern family, not for each new playbook. printf '| Named waste pattern (e.g. zombie NAT, snapshot sprawl, idle or orphaned VMs and disks, expiring commitments, storage cold data, GPU sizing, agent loops, log ingestion) | %s |\n' 'playbook-.md, matched on the file name (e.g. playbook-aws-zombie-nat-gateway.md)' cat <<'EOF' | What does model X / instance Y cost right now (a current price figure, not a billing mechanic) | No knowledge file - send the user to https://optimtoken.optimnow.io (OptimNow AI Pricing Hub). Never answer from a figure remembered from a knowledge file. | For multi-domain queries, retrieve all relevant files and synthesise. For named waste patterns, retrieve the matching `playbook-.md` knowledge file. EOF emit_instructions_tail "see Reasoning Methodology Appendix in finops-for-ai.md" "domain" } build_grouped_instructions() { cat <<'EOF' # Cloud FinOps Expert Assistant You are an expert FinOps practitioner. Help users understand and optimise spend on cloud (AWS / Azure / GCP / OCI), AI platforms (Anthropic, Bedrock, Azure OpenAI / Foundry, Vertex AI, open-weight vendor APIs such as DeepSeek / Qwen / Kimi / GLM), data platforms (Databricks, Microsoft Fabric, Snowflake), AI coding tools (Cursor, Claude Code, Copilot, Codex, Windsurf, Gemini Code Assist), SaaS, and cross-cutting concerns (tagging, FinOps Framework, GreenOps, ITAM, anomaly management, allocation/showback, chargeback, onboarding, Kubernetes, waste detection, KPIs and benchmarking, forecasting, FinOps practice operations (operating model, RACI, governance, ITFM), on-premises and hybrid FinOps, FOCUS multi-cloud cost data). Your knowledge files are grouped thematically and updated weekly. Always retrieve the relevant grouped file before answering - do not rely on general training data for billing specifics. ## Domain routing (grouped layout) Use these knowledge files for the following query types: | Query topic | Knowledge file | |---|---| | AWS cost management, EC2, RIs, Savings Plans, EDP, RDS, Bedrock pricing, Application Inference Profiles | aws.md | | Azure cost management, Reservations, Savings Plans, AHB, MACC, AKS, MCA, Azure OpenAI / Foundry PTUs | azure.md | | GCP cost management, BigQuery export, CUDs, SUDs, Spot, Carbon Footprint, Vertex AI / Gemini Enterprise Agent Platform, Gemini pricing, Flexible Savings Plans, AI Studio | gcp.md | | AI cost management, LLM economics, agentic patterns, ROI, Anthropic billing, open-weight vendor hosted APIs (DeepSeek / Qwen / Kimi / GLM), time-based pricing, open-weight licensing, AI coding tools (Cursor / Copilot / Claude Code / Codex / Windsurf), GenAI capacity, AI Investment Council, self-hosted vs managed inference | ai.md | | Databricks (DBCU, allocation, Photon), Microsoft Fabric (F-SKUs, CU smoothing), Snowflake (QUERY_ATTRIBUTION_HISTORY, Cortex) | data-platforms.md | | OCI (Cost Reports, FOCUS, cost-tracking tags, Universal Credits) | oci.md | | FinOps Framework 2026 (4 domains, 22 capabilities), tagging, SaaS management, ITAM, cloud contract negotiation (EDP, MACC, Google commitments), GreenOps, Kubernetes FinOps, waste detection playbooks, FOCUS multi-cloud cost data normalisation and ingestion, on-premises and hybrid FinOps (internal bill, Outposts, Azure Local, VMware, exit fees) | cross-cutting.md | | Anomaly management, allocation and showback, chargeback (incl. Finance / accounting prerequisites), onboarding workloads (migration-time cost hygiene, M&A, divestiture), KPIs and benchmarking, forecasting, FinOps practice operations (operating model, RACI, governance, ITFM), executive reporting | finops-discipline.md | EOF emit_named_pattern_row 'playbooks.md' cat <<'EOF' | Reasoning methodology lens (diagnose before prescribing, connect cost to value, recommend progressively) | methodology.md | | What does model X / instance Y cost right now (a current price figure, not a billing mechanic) | No knowledge file - send the user to https://optimtoken.optimnow.io (OptimNow AI Pricing Hub). Never answer from a figure remembered from a knowledge file. | For multi-domain queries, retrieve all relevant grouped files and synthesise. For named waste patterns, look up the matching `## playbook: ` section inside `playbooks.md`. EOF emit_instructions_tail "methodology.md" "grouped" } install_gemini() { local outdir="${DEST_OVERRIDE:-$PWD}/dist/gemini" local instructions_path="$outdir/instructions.md" local knowledge_dir="$outdir/knowledge" if [[ -n "$DRY_RUN" ]]; then info "DRY-RUN would write: $instructions_path" info "DRY-RUN would write: $knowledge_dir/*.md" return fi # Wipe any previous build so renamed/removed references don't linger rm -rf "$knowledge_dir" mkdir -p "$knowledge_dir" # Gemini always uses the grouped knowledge layout, so the routing contract # must point at the grouped filenames - not the per-reference names that # the ChatGPT default uses. build_grouped_instructions > "$instructions_path" build_gemini_grouped_knowledge "$knowledge_dir" local file_count file_count=$(find "$knowledge_dir" -maxdepth 1 -name "*.md" | wc -l | tr -d ' ') ok "Gemini Gems: instructions -> $instructions_path" ok "Gemini Gems: $file_count grouped knowledge files -> $knowledge_dir/" dim " Manual upload: https://gemini.google.com/gems/ - paste instructions, upload knowledge files." dim " Note: references are grouped by domain to fit Gemini's tighter file cap." } build_gemini_grouped_knowledge() { local outdir="$1" local refs="$SRC_DIR/plugins/cloud-finops/skills/cloud-finops/references" # cat_required [ ...] # Concatenates the inputs into the output. Fails loudly if any input is # missing - silent omission would let a renamed reference disappear from a # grouped artefact without the maintainer noticing, defeating the purpose # of the grouped build as a fallback path for capped uploads. cat_required() { local out="$1"; shift local f for f in "$@"; do if [[ ! -f "$f" ]]; then err "build_gemini_grouped_knowledge: missing input '$f' for $(basename "$out")" return 1 fi done cat "$@" > "$out" } cat_required "$outdir/aws.md" \ "$refs/finops-aws.md" "$refs/finops-aws-billing.md" \ "$refs/finops-aws-commitments.md" \ "$refs/finops-aws-patterns-compute.md" "$refs/finops-aws-patterns-storage.md" \ "$refs/finops-aws-patterns-databases.md" "$refs/finops-aws-patterns-networking.md" \ "$refs/finops-aws-patterns-other.md" "$refs/finops-bedrock.md" cat_required "$outdir/azure.md" \ "$refs/finops-azure.md" "$refs/finops-azure-billing.md" \ "$refs/finops-azure-commitments.md" \ "$refs/finops-azure-patterns.md" "$refs/finops-azure-openai.md" cat_required "$outdir/gcp.md" \ "$refs/finops-gcp.md" "$refs/finops-vertexai.md" cat_required "$outdir/ai.md" \ "$refs/finops-for-ai.md" "$refs/finops-anthropic.md" "$refs/finops-ai-dev-tools.md" \ "$refs/finops-genai-capacity.md" "$refs/finops-ai-value-management.md" \ "$refs/finops-ai-self-hosted-vs-managed.md" \ "$refs/finops-open-weight-vendors.md" \ "$refs/finops-agentic.md" cat_required "$outdir/data-platforms.md" \ "$refs/finops-databricks.md" "$refs/finops-fabric.md" "$refs/finops-snowflake.md" cat_required "$outdir/oci.md" \ "$refs/finops-oci.md" cat_required "$outdir/cross-cutting.md" \ "$refs/finops-framework.md" "$refs/finops-tagging.md" "$refs/finops-sam.md" \ "$refs/finops-itam.md" "$refs/finops-cloud-contracts.md" "$refs/greenops-cloud-carbon.md" \ "$refs/finops-kubernetes.md" "$refs/finops-waste-detection-playbooks.md" \ "$refs/finops-focus.md" "$refs/finops-on-prem-hybrid.md" cat_required "$outdir/finops-discipline.md" \ "$refs/finops-anomaly-management.md" "$refs/finops-allocation-showback.md" \ "$refs/finops-chargeback.md" "$refs/finops-onboarding-workloads.md" \ "$refs/finops-kpis-benchmarking.md" "$refs/finops-forecasting.md" \ "$refs/finops-practice-operations.md" cat_required "$outdir/methodology.md" \ "$refs/optimnow-methodology.md" # Playbooks bundle: SKILL.md routes named-pattern queries to # playbooks/.md, so the grouped artefact must include the # playbook content too. Bundled into a single playbooks.md to keep # the grouped layout's 1-bundle-per-domain shape. local playbooks="$SRC_DIR/plugins/cloud-finops/skills/cloud-finops/playbooks" if [[ -d "$playbooks" ]]; then { echo "# Cloud FinOps Playbooks Bundle" echo echo "Each section below is a self-contained named-pattern runbook." echo "When SKILL.md routes a 'named waste pattern X' query to" echo "\`playbooks/.md\`, look up the section here whose title" echo "matches the slug." echo for pb in "$playbooks"/*.md; do local pb_name pb_name=$(basename "$pb") # README.md is the format / contributor guide, not a runbook [[ "$pb_name" == "README.md" ]] && continue echo "---" echo echo "## playbook: ${pb_name%.md}" echo cat "$pb" echo done } > "$outdir/playbooks.md" fi } install_gemini_cli() { local target if [[ -n "$DEST_OVERRIDE" ]]; then target="$DEST_OVERRIDE/$SKILL_NAME" else target="$HOME/.gemini/skills/$SKILL_NAME" fi do_copy_dir "$SRC_DIR/plugins/cloud-finops/skills/cloud-finops" "$target" ok "Gemini CLI: skill copied -> $target" dim " Gemini CLI implements the SKILL.md standard - it discovers user skills in" dim " ~/.gemini/skills/ and reads SKILL.md one directory deep, which is this layout." dim " For a project-scoped install instead: --dest .gemini/skills" } install_codex() { local default_target="${DEST_OVERRIDE:-$PWD}/AGENTS.md" local target="$default_target" if [[ -f "$target" ]] && ! is_ours "$target"; then warn "Codex: $target exists and was not written by this installer." warn " Writing to AGENTS-cloud-finops.md instead." target="${DEST_OVERRIDE:-$PWD}/AGENTS-cloud-finops.md" fi do_write "$target" build_codex_agents_md ok "Codex CLI: agent context written -> $target" dim " Codex reads AGENTS.md from project root. If AGENTS-cloud-finops.md was used," dim " manually merge into your existing AGENTS.md (or rename when ready)." routing_hint } build_codex_agents_md() { cat < $target" dim " Aider auto-reads CONVENTIONS.md. Pull individual references at runtime:" dim " aider --read plugins/cloud-finops/skills/cloud-finops/references/finops-bedrock.md ..." routing_hint } build_aider_conventions() { cat <.md`, or wire up the cloud-finops MCP server and fetch on demand. EOF write_body } install_copilot() { local default_target="${DEST_OVERRIDE:-$PWD}/.github/copilot-instructions.md" local target="$default_target" # The same provenance guard install_codex and install_aider use, and the one # target that needed it most. detect_copilot fires only when # .github/copilot-instructions.md ALREADY exists, and this function used to # call do_write unconditionally - so the single situation auto-detect mode # could act on was one where it destroyed a file the user had written by # hand. Now a file that is not ours is left alone and the build goes to a # suffixed name, exactly as with AGENTS.md and CONVENTIONS.md. if [[ -f "$target" ]] && ! is_ours "$target"; then warn "Copilot: $target exists and was not written by this installer." warn " Writing to copilot-instructions-cloud-finops.md instead." target="${DEST_OVERRIDE:-$PWD}/.github/copilot-instructions-cloud-finops.md" fi do_write "$target" build_copilot_instructions ok "Copilot: instructions written -> $target" if [[ "$target" != "$default_target" ]]; then dim " Copilot reads .github/copilot-instructions.md. Merge the generated file" dim " into yours (or rename it when ready) - Copilot will not read it as is." fi warn "Copilot fit is limited - the instruction surface is shallow. The skill informs" warn " code-suggestion context but won't power deep FinOps Q&A like Claude / Cursor do." } build_copilot_instructions() { # The provenance marker must be inside the first 20 lines - that is the window # is_ours() inspects - so it goes directly under the H1, as in the codex and # aider builders. Without it a re-run cannot recognise its own output and # would fork to a suffixed file on every invocation. cat < $target" dim " Kiro reads POWER.md as the entry point." } install_mcp() { # Print install hint + per-client config snippets. We intentionally do NOT # run pip from a shell installer. printf "${C_BOLD}Cloud FinOps MCP server${C_RESET}\n" dim " Adds six queryable tools across two surfaces:" dim " references: list_references / get_reference / find_references" dim " (faceted by FinOps Capability/Phase frontmatter)" dim " playbooks: list_playbooks / get_playbook / find_playbooks" dim " (faceted by scope / service / waste_category / confidence)" printf "\n" printf "${C_BOLD}Step 1${C_RESET} - install the server (Python 3.10+):\n" printf " pip install cloud-finops-mcp\n" printf " ${C_DIM}# or, no install: ${C_RESET}uvx cloud-finops-mcp\n" printf "\n" printf "${C_BOLD}Step 2${C_RESET} - add to your MCP client config:\n" printf "\n" printf " ${C_BOLD}Claude Code${C_RESET} (user scope - one command, no file editing):\n" printf " claude mcp add --scope user cloud-finops -- cloud-finops-mcp\n" printf "\n ${C_BOLD}Claude Code${C_RESET} (project scope - .mcp.json at project root):\n" cat <<'EOF' { "mcpServers": { "cloud-finops": { "command": "cloud-finops-mcp" } } } EOF dim " Note: ~/.claude/mcp.json is NOT read by Claude Code. User-scope config" dim " lives in ~/.claude.json - use the command above rather than editing it." printf "\n ${C_BOLD}Cursor${C_RESET} (~/.cursor/mcp.json):\n" cat <<'EOF' { "mcpServers": { "cloud-finops": { "command": "cloud-finops-mcp" } } } EOF printf "\n ${C_BOLD}Codex CLI${C_RESET} (~/.codex/config.toml):\n" cat <<'EOF' [mcp_servers.cloud-finops] command = "cloud-finops-mcp" EOF printf "\n ${C_BOLD}Windsurf${C_RESET} (~/.windsurf/mcp.json):\n" cat <<'EOF' { "mcpServers": { "cloud-finops": { "command": "cloud-finops-mcp" } } } EOF printf "\n" printf "${C_BOLD}Step 3${C_RESET} - restart your client. Verify:\n" dim " Claude Code: /mcp" dim " Cursor: chat panel will list cloud-finops as an available MCP" dim " Codex CLI: codex mcp list" printf "\n" dim " PyPI: https://pypi.org/project/cloud-finops-mcp/" dim " Source: https://github.com/OptimNow/cloud-finops-skills/tree/main/mcp_server" } install_tool() { case "$1" in claude-code) install_claude_code ;; claude-projects) install_claude_projects ;; cursor) install_cursor ;; windsurf) install_windsurf ;; chatgpt) install_chatgpt ;; gemini) install_gemini ;; gemini-cli) install_gemini_cli ;; codex) install_codex ;; aider) install_aider ;; copilot) install_copilot ;; kiro) install_kiro ;; mcp) install_mcp ;; *) err "Unknown tool: $1"; return 1 ;; esac } list_tools() { echo "Supported tools:" for t in "${ALL_TOOLS[@]}"; do echo " - $t" done } main() { while [[ $# -gt 0 ]]; do case "$1" in --tool) TOOL="${2:?--tool requires a value}"; shift 2 ;; --dry-run) DRY_RUN=1; shift ;; --user) USER_LEVEL=1; shift ;; --grouped) GROUPED=1; shift ;; --inline) INLINE=1; shift ;; --dest) DEST_OVERRIDE="${2:?--dest requires a value}"; shift 2 ;; --list) list_tools; exit 0 ;; --help|-h) usage 0 ;; *) err "Unknown option: $1"; echo; usage 1 ;; esac done resolve_source printf "\n${C_BOLD}Cloud FinOps Skill & MCP - cross-tool installer${C_RESET}\n" dim " Source: $SRC_DIR/plugins/cloud-finops/skills/cloud-finops/" printf "\n" local selected=() if [[ -n "$TOOL" && "$TOOL" != "all" ]]; then local valid=false t for t in "${ALL_TOOLS[@]}"; do [[ "$t" == "$TOOL" ]] && valid=true && break done if ! $valid; then err "Unknown tool: $TOOL" list_tools exit 1 fi selected=("$TOOL") elif [[ "$TOOL" == "all" ]]; then selected=("${ALL_TOOLS[@]}") else local t for t in "${ALL_TOOLS[@]}"; do if is_detected "$t" 2>/dev/null; then selected+=("$t") printf " ${C_GREEN}[*]${C_RESET} %s detected\n" "$t" else printf " ${C_DIM}[ ] %s not detected${C_RESET}\n" "$t" fi done if [[ ${#selected[@]} -eq 0 ]]; then printf "\n" warn "No tools auto-detected. Use --tool or --tool all." dim " Run --list to see supported tools." exit 0 fi printf "\n" fi local t for t in "${selected[@]}"; do install_tool "$t" done printf "\n" if [[ -n "$DRY_RUN" ]]; then printf "${C_BLUE}[DRY]${C_RESET} Dry run complete - nothing was written. Targets: ${selected[*]}\n" else printf "${C_GREEN}[OK]${C_RESET} Done. Installed for: ${selected[*]}\n" fi dim " Source: https://github.com/OptimNow/cloud-finops-skills (CC BY-SA 4.0)" } main "$@"