finfocus
CLAUDE.md10 starsChanged 2 months agoApache-2.0View on GitHub
DO NOT RUN git commit - This is explicitly forbidden. Use git add, git status, git diff, and git log only. The user will commit manually. ALWAYS run make lint and make test before claiming success. DO NOT modify .golangci.yml without explicit approval. FinFocus Core is a CLI tool and plugin host system for calculating cloud infrastructure costs from Pulumi infrastructure definitions. It provides both projected cost estimates and actual historical cost analysis through a plugin-based architecture. Feature specs, plans,…
- Reads credentials
In this repository7 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .github/copilot-instructions.mdCopilot instructions
- pick-issueSkill
- promote-issueSkill
- agentic-workflow-designerSkill
- agentic-workflowsSkill
- jqschemaSkill
The file
Show its rules and text
We split this CLAUDE.md into the rules it gives an agent
47 rules. About 0 are common, 23 are distinctive, and 24 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈23
Distinctive · estimate
This author's own choices. Worth a look.
24
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 9
ALWAYS run
make lintandmake test: before claiming success. - Distinctive: line 76
Unit tests: Must achieve 80% coverage minimum
- Distinctive: line 77
Critical paths: Must achieve 95% coverage
- Distinctive: line 78
All error paths: Must be tested
- Distinctive: line 79
Performance regressions: Must be detected via benchmarks
- Distinctive: line 80
Integration scenarios: Must include plugin communication flows
- Distinctive: line 81
End-to-end workflows: Must test complete CLI usage
- Distinctive: line 94
CRITICAL: Before claiming any Go version "doesn't exist" or suggesting version changes, verify on <https://go.dev/dl/> first.
- Distinctive: line 102
If any runtime instruction conflicts with a constitution principle:
- Distinctive: line 104
Constitution wins: - Follow the constitution rule
- Very specific: line 105
Use
/speckit.revisit: - Document the conflict for prevention - Very specific: line 144
Use RunE not Run for error handling
- Very specific: line 145
Use cmd.Printf() for output (not fmt.Printf())
- Very specific: line 194
After modifying internal/tui/ code, ALWAYS:
- Distinctive: line 197
Verify column alignment, section ordering, and data population visually
- Very specific: line 198
Run golden file tests: go test -run TestGolden ./internal/tui/...
- Very specific: line 210
Not parallel: t.Setenv, t.Chdir, os.Setenv, swapping a package-level variable, config.ResetGlobalConfigForTest/SetGlobalConfig, or anything …
- Very specific: line 215
Not parallel: a test that writes a script or binary (#!/bin/sh, os.WriteFile or os.Chmod with exec bits) and then executes it, directly or …
- Distinctive: line 219
Only the executing test needs to be sequential, because sequential tests never overlap parallel ones.
- Very specific: line 227
Do not use defer in a parent test that starts parallel subtests.
- Very specific: line 229
Verify with go test -race -shuffle=on -count=3 ./<pkg>/....
- Distinctive: line 245
Never simulate cost values or stub CLI execution.
- Very specific: line 252
Expected errors: Use t.Logf() (informational, test passes), NOT t.Errorf()
- Very specific: line 253
Required errors: Use t.Fatalf("expected error") only if error is absent
- Distinctive: line 257
If CI shows these errors in logs but tests are marked PASS, the behavior is correct.
- Distinctive: line 258
Only investigate if tests actually FAIL (exit code 1).
- Distinctive: line 262
When writing new code, always include tests for error conditions:
- Distinctive: line 264
Test every error return path
- Distinctive: line 266
Test boundary conditions: empty inputs, nil pointers, invalid ranges
- Distinctive: line 267
Test partial failures in batch operations
- Distinctive: line 268
Test resource cleanup runs even when errors occur (defer patterns)
- Very specific: line 272
CRITICAL: All Go tests MUST use testify's require and assert packages.
- Very specific: line 273
NEVER use manual if x != y { t.Errorf(...) } patterns.
- Distinctive: line 296
Run Core E2E tests to verify
- Very specific: line 344
No credential or Pulumi secret reaches a plugin through tags: ConvertToProto drops credential-like top-level keys (isCredentialKey, the one …
- Very specific: line 387
If ingestion fails to populate Inputs, these fields are empty.
- Very specific: line 476
Zombie prevention: Always call cmd.Wait() after cmd.Process.Kill()
- Very specific: line 547
Region-specific binaries: When plugin.metadata.json has a region key, registry looks for finfocus-plugin-<name>-<region> first, then falls …
- Very specific: line 549
Checksum verification: Only a confirmed hash mismatch is fatal.
- Distinctive: line 577
Only nil/empty results trigger fallback to the next plugin
- Very specific: line 796
Every field on OverviewRow has a specific temporal basis, population rule, and set of valid comparisons.
- Very specific: line 833
Use CalculateRowDelta() — it encodes status-aware logic:
- Distinctive: line 850
Do not unify these. Delta uses 30-day for stable comparisons across months.
- Very specific: line 879
When no preview is provided, overview shows state resources with * footnote on projected costs.
- Very specific: line 912
When both fields are share, idle is distributed first (including onto system rows) and system rows are folded after that
- Distinctive: line 1051
Always diff the integration failure *set* against a pre-change baseline rather than comparing failure counts
- Very specific: line 1053
Overriding
HOMEfor ago/makechild moves Go's caches: when GOPATH is not exported (CI), HOME=<t.TempDir()> puts the module cache …
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
CRITICAL INSTRUCTIONS
DO NOT RUN git commit - This is explicitly forbidden. Use git add, git status, git diff, and git log only. The user will commit manually.
ALWAYS run make lint and make test before claiming success.
DO NOT modify .golangci.yml without explicit approval.
Project Overview
FinFocus Core is a CLI tool and plugin host system for calculating cloud infrastructure costs from Pulumi infrastructure definitions. It provides both projected cost estimates and actual historical cost analysis through a plugin-based architecture.
Specs
Feature specs, plans, and tasks live in specs/NNN-*/ and are produced by the
Spec Kit pipeline (.specify/ templates, .specify/memory/constitution.md,
and the /speckit-* skills). Spec Kit is the ONLY spec/plan/task pipeline:
design or plan output from other tools (e.g. superpowers brainstorming or
writing-plans) MUST be converted into Spec Kit feature folders under specs/
before implementation, not committed elsewhere in the repo.
Build Commands
make tools # Install toolchain pinned in mise.toml (first-time setup)
make build # Build binary to bin/finfocus
make test # Run unit tests (default, fast)
make test-race # Run with race detector
make test-integration # Integration tests (slower)
make test-e2e # E2E tests (requires AWS credentials)
make lint # Run golangci-lint + markdownlint
make validate # go mod tidy, go vet
make clean # Remove build artifacts
make run # Build and run with --help
make dev # Build and run without args
make docs-lint # Lint markdown docs
make docs-build # Build Jekyll site
make docs-serve # Serve docs at http://localhost:4000/finfocus/
make build-recorder # Build recorder plugin to bin/finfocus-plugin-recorder
make install-recorder # Build and install recorder to ~/.finfocus/plugins/recorder/0.1.0/
make test-jev # Test the jev scorer plugin module (plugins/jev, separate go.mod)
make install-jev # Build and install the jev scorer pluginSingle Package/Test Commands
go test -v ./internal/cli/... # Test specific package
go test -v ./internal/engine/... # Test engine package
go test -run TestSpecificFunction ./... # Run specific test
# Coverage
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out # View in browser
# Plugin management
./bin/finfocus plugin list
./bin/finfocus plugin list --output json # JSON array for machine consumption
./bin/finfocus plugin validateTroubleshooting
pkill golangci-lint || true # Fix parallel linting conflicts
GOOS=linux GOARCH=amd64 make build # Test release build locally
gh workflow validate .github/workflows/ci.yml # Validate workflow syntaxTest Requirements
- Unit tests: Must achieve 80% coverage minimum
- Critical paths: Must achieve 95% coverage
- All error paths: Must be tested
- Performance regressions: Must be detected via benchmarks
- Integration scenarios: Must include plugin communication flows
- End-to-end workflows: Must test complete CLI usage
Never complete a project without running:
make test # Run all tests
make lint # Run lintingGo Version
Project Go Version: 1.27.1 (see go.mod)
CRITICAL: Before claiming any Go version "doesn't exist" or suggesting version changes, verify on https://go.dev/dl/ first.
Constitution Precedence Rule
CRITICAL: The constitution (.specify/memory/constitution.md) takes absolute
precedence over all runtime mode instructions (learning mode, explanatory mode, etc.).
If any runtime instruction conflicts with a constitution principle:
- Constitution wins - Follow the constitution rule
- Use
/speckit.revisit- Document the conflict for prevention - Never compromise - Principle VI forbids TODOs/stubs regardless of mode
Architecture
Core components and their directories:
- CLI (
internal/cli/) - Cobra commands: cost projected/actual/recommendations, plugin management, analyzer - Engine (
internal/engine/) - Cost calculation orchestration, output rendering (table/JSON/NDJSON) - Plugin Host (
internal/pluginhost/) - gRPC plugin lifecycle (launch, connect, cleanup) - Registry (
internal/registry/) - Plugin discovery in~/.finfocus/plugins/<name>/<version>/ - Ingestion (
internal/ingest/) - Pulumi plan JSON parsing - Analyzer (
internal/analyzer/) - Pulumi Analyzer gRPC protocol for zero-click cost estimation - TUI (
internal/tui/) - Bubble Tea terminal UI components - Router (
internal/router/) - Intelligent plugin routing with priority and fallback - Config (
internal/config/) - Two-tier configuration (project-local overrides global)
Configuration Resolution
Project-specific settings (config, dismissals) precedence:
--project-dirflag (explicit override)FINFOCUS_PROJECT_DIRenv var- Walk up from CWD to find
Pulumi.yaml, use$PROJECT/.finfocus/ - Fall back to
~/.finfocus/(backward compatible)
Global resources (plugins, cache, logs) precedence:
FINFOCUS_HOMEenv varPULUMI_HOME/finfocus~/.finfocus/
Config Merge: Project config.hujson overrides global config.hujson at the top-level key level
(shallow merge). Keys absent in project config inherit from global defaults. Legacy config.yaml files are auto-migrated to Hujson format on first read.
Key Patterns
CLI Conventions
- Use
RunEnotRunfor error handling - Use
cmd.Printf()for output (notfmt.Printf()) - Defer cleanup functions immediately after obtaining resources
- Support multiple date formats: "2006-01-02", RFC3339
Pre-Flight Request Validation
The adapter layer (internal/proto/) validates requests using pluginsdk validation
before gRPC calls. Key points:
- Validation happens in
GetProjectedCostWithErrors()andGetActualCostWithErrors() - Uses "VALIDATION:" prefix to distinguish from plugin errors ("ERROR:")
- Logs at WARN level with resource context for debugging
- Returns placeholder CostResult with $0 cost and descriptive Notes
- Invalid resources are skipped; valid resources still call the plugin
- A projected resource with
ref.*tags and an empty SKU uses lenient validation (pluginsdk.ValidateProjectedCostRequestLenient) instead of failing closed on SKU
Logging
# Enable debug output
finfocus cost projected --debug --pulumi-json plan.json
export FINFOCUS_LOG_LEVEL=debug
export FINFOCUS_LOG_FORMAT=json # json or console
export FINFOCUS_TRACE_ID=external-trace-123 # inject external trace IDPrecedence: CLI flags (--debug) > env vars > config file > default (info, console).
Global Agentic Flags
The following flags are automatically mounted by ax.Execute on all commands:
--format json|human: Output format for machine vs human consumption (JSON for agent/tooling, human for terminal). When set tojson, some commands automatically output machine-readable JSON. Defaults to auto-detection via TTY.--dry-run: Preview changes without making them (skip real side effects). Affects mutating commands:plugin install/update/remove,analyzer install/uninstall,config init/set, and recommendation operations (dismiss/snooze/undismiss), andplugin upgrade.--yes: Skip confirmation prompts (equivalent to-yor--forceon individual commands). Automatically confirms operations that normally require user approval.--idempotency-key string: Opaque retry-deduplication key for preventing duplicate-create operations in distributed systems.--debug: Enable debug logging (also available as persistent flag for CLI-specific control).
Additionally, the following utility commands are available:
__schema [--as=ax|mcp]: Emit machine-discoverability schema in AX (default) or MCP format for tool discovery.mcp-server [--transport=stdio|http] [--addr] [--allow-non-loopback]: Expose the entire CLI as a live Model Context Protocol server.--mcp(root-local flag): stdio alias formcp-server; same tool list. User docs:docs/src/content/docs/guides/mcp.md.
Testing
TUI Visual Verification
After modifying internal/tui/ code, ALWAYS:
- Render the affected view and read the full output (not just test pass/fail)
- Verify column alignment, section ordering, and data population visually
- Run golden file tests:
go test -run TestGolden ./internal/tui/... - Regenerate golden files if layout intentionally changed:
UPDATE_GOLDEN=1 go test -run TestGolden ./internal/tui/...
String-only assertions (assert.Contains) are NOT sufficient for TUI testing.
Parallel Tests
Tests call t.Parallel() (top level and each t.Run subtest) unless they touch
process-wide state. Parallel tests only run after every sequential test in the
package has finished, so the hazard is parallel tests interfering with each other.
- Not parallel:
t.Setenv,t.Chdir,os.Setenv, swapping a package-level variable,config.ResetGlobalConfigForTest/SetGlobalConfig, or anything that builds a root command (NewRootCmd*sets the process-wide resolved project directory throughconfig.SetResolvedProjectDir). This includes helpers that call those, such asstubHomeorWithEnv. - Not parallel: a test that writes a script or binary (
#!/bin/sh,os.WriteFileoros.Chmodwith exec bits) and then executes it, directly or through a helper or launcher. A concurrent fork in the same process lets the child inherit the open write fd, so the exec fails withtext file busy(ETXTBSY, golang/go#22315). Only the executing test needs to be sequential, because sequential tests never overlap parallel ones. - Mark such a test with
//nolint:paralleltest // <specific reason>on the line abovefunc. Put the directive on thet.Runorforline instead when only some subtests must stay sequential.nolintlintrequires the reason. - Table-driven subtests must not share a mutable fixture. Production code mutates
proto messages and slices in place (for example
Engine.GetBudgetson a shared*pbc.Budget), so build the fixture inside the subtest. - Do not use
deferin a parent test that starts parallel subtests; uset.Cleanup. The defer runs before the paused subtests resume. - Verify with
go test -race -shuffle=on -count=3 ./<pkg>/.... A flake or race means the test is not safe to parallelise.
E2E Testing
Location: test/e2e/ (separate Go module)
Prerequisites: AWS session or profile configured, Pulumi CLI, make build
export PATH="$HOME/.pulumi/bin:$PATH"
export PULUMI_CONFIG_PASSPHRASE="e2e-test-passphrase"
make test-e2eCRITICAL: E2E tests MUST call actual finfocus CLI binary. Never simulate cost values or stub CLI execution.
Expected Failure Test Patterns
IMPORTANT: Tests that intentionally create failing plugin scenarios must follow these patterns to avoid false CI failures:
- Expected errors: Use
t.Logf()(informational, test passes), NOTt.Errorf() - Required errors: Use
t.Fatalf("expected error")only if error is absent - Common expected errors:
context deadline exceeded,connection refused,broken pipe/EOF,no such file or directory
If CI shows these errors in logs but tests are marked PASS, the behavior is correct. Only investigate if tests actually FAIL (exit code 1).
Error Path Testing
When writing new code, always include tests for error conditions:
- Test every error return path
- Validate error messages with
assert.Contains(t, err.Error(), "expected text") - Test boundary conditions: empty inputs, nil pointers, invalid ranges
- Test partial failures in batch operations
- Test resource cleanup runs even when errors occur (defer patterns)
Testify Assertion Standards
CRITICAL: All Go tests MUST use testify's require and assert packages.
NEVER use manual if x != y { t.Errorf(...) } patterns.
require.* (stops test on failure): Setup operations, error checks where
continuing would panic, non-nil checks before use.
assert.* (continues on failure): Value comparisons, multiple property
checks, non-critical validations.
| Manual Pattern | Testify Replacement |
if err != nil { t.Fatal(err) } | require.NoError(t, err) |
if err == nil { t.Error("expected error") } | require.Error(t, err) |
if x != y { t.Errorf("got %v, want %v", x, y) } | assert.Equal(t, y, x) |
if len(x) != n { t.Errorf(...) } | assert.Len(t, x, n) |
if !strings.Contains(s, sub) { t.Errorf(...) } | assert.Contains(t, s, sub) |
if x == nil { t.Fatal("nil") } | require.NotNil(t, x) |
Local Plugin Development
- Clone the plugin repository (e.g.,
finfocus-plugin-aws-public) - Modify the plugin code (add logging, fix type mapping)
- Build:
make build-region REGION=us-east-1 - Install: Copy binary to
~/.finfocus/plugins/<plugin>/<version>/ - Run Core E2E tests to verify
Important Files
cmd/finfocus/main.go- CLI entry point, routed throughax.Execute(ax-go). Exit codes: 0=success, 1=generic/internal error (axExitInternal), and a user-configurable code (default 1, 0-255 viacost --exit-code/--exit-on-threshold) for budget-exceeded, preserved throughax.Executeviainternal/cli.toAxExitError.ax.ExitValidation(2)/ExitNetwork(3)/ExitAuth(4) are ax-go's own reserved exit codes for new error classifications, not yet used anywhere in finfocus, and not retrofitted onto existing exit-1 paths.internal/engine/engine.go- Core orchestrationinternal/pluginhost/host.go- Plugin client managementinternal/ingest/pulumi_plan.go- Pulumi plan parsing.specify/memory/constitution.md- Project principles and quality gatesexamples/plans/aws-simple-plan.json- Sample plan for testing
Pulumi Integration Notes
Plan JSON Parsing
The pulumi preview --json output nests resource details under newState.
Ingestion MUST inspect newState to extract inputs and type. Without this,
property extraction fails and plugins return InvalidArgument errors.
newState and stack-export resources also carry parent, dependencies, and
propertyDependencies. parent is the Pulumi stack, not a pricing reference.
ApplyCrossResourceRefs follows propertyDependencies only: a property that
points at exactly one in-plan resource becomes ref.<property>.{urn,type,region,sku}
tags. The Pulumi unknown sentinel 04da6b54-80e4-46f7-96ec-b56ff0331ba9 is never
sent as a tag, SKU, or region. A child's own region is filled from the referenced
resource only when the child has none and exactly one referenced resource has a
region. The referenced SKU is never copied into the child's Sku. A child with
ref.* tags and an empty SKU uses ValidateProjectedCostRequestLenient so the
plugin still sees the tags. Classic Azure skuName is copied only into
ref.<property>.sku (the provider resolver does not treat skuName as the
resource's own SKU). Projected cache keys append /refs-<hash> when those tags
exist. Spec: specs/618-cross-resource-refs/.
ConvertToProto also emits dotted keys for nested maps and arrays
(sku.capacity, rootBlockDevice.0.volumeType) beside each collapsed key.
It skips __ segments, credential-like segments (password, passwd,
passphrase, secret, token, credential, ciphertext, privatekey,
apikey, accesskey, connectionstring, with the snake_case forms), a
top-level input named ref
(so it cannot flatten into the ref.* reference namespace), and the containers
tags, tagsAll, labels, and annotations. Depth is capped at 6
segments, new keys at 128 characters, new values at 256 characters, and the
whole tag map at 50 entries. Existing collapsed keys are kept first.
No credential or Pulumi secret reaches a plugin through tags: ConvertToProto
drops credential-like top-level keys (isCredentialKey, the one rule shared
with dotted keys and attributes) and secret values, the dotted walk skips
secret maps (a decrypted secret's value leaf), ConvertValueToString
returns "" for a secret and leaves credential keys and secrets out of
collapsed map and slice text, actual-cost tags drop secret values, and
EstimateCost attributes go through redactedProperties.
Projected cache keys always append /tags-<digest> of that map, then
/refs-<hash> when reference tags exist. EstimateCost attributes stay
nested. Spec: specs/619-dotted-tag-keys/.
Core also sends the raw properties as ResourceDescriptor.attributes
(finfocus-spec v0.7.3), built by engine.BuildAttributes. They go on projected
GetProjectedCost and BatchCost, Supports, GetPricingSpec, actual
BatchCost, and GetActualCostRequest.resource (finfocus-spec v0.7.4). At any depth they drop keys skipDottedSegment rejects (__
and credential-like names) and Pulumi secrets (history.IsPulumiSecret, the one
shared rule). At the top level they drop ref and ref.*. Pulumi unknowns and
the tags/labels containers are kept. Over pluginsdk.MaxAttributesBytes
(65536), they are omitted with a warning. Projected cache keys add
/attrs-<digest> after /refs-, and the in-memory Supports key adds
:attrs-<digest>, so Supports runs about once per distinct resource. A
projected BatchCost chunk is also split so its descriptors stay under
maxBatchRequestBytes (3 MiB; grpc-go's default limit is 4 MiB). Tags are
unchanged. Spec: specs/621-k8s-workload-projected-cost/.
GetActualCostRequest.resource is built by proto.actualCostDescriptor from
GetActualCostRequest.Resource with PrepareProjectedDescriptor, as the spec
requires. It is optional enrichment: it is dropped (warn log, request still
sent) when the request names more than one resource, provider or type is
empty, or pluginsdk.ValidateResourceDescriptor rejects it, never a
VALIDATION placeholder. Request tags keep the injected sku/region/
provider/resource_type for plugins older than v0.7.4. Actual cache keys add
a descriptor filter (per-resource digest of flattened tags, ref.* included,
and attributes; actualDescriptorCacheSuffix) only when a resource would send
descriptor content, so resources without one keep their existing keys.
Property Extraction
The adapter (internal/proto/adapter.go) relies on the Inputs map to extract:
- SKU: from
instanceType,type, etc. - Region: from
availabilityZone,region
If ingestion fails to populate Inputs, these fields are empty.
Resource Type Compatibility
Pulumi provides types like aws:ec2/instance:Instance (Type Token). Plugins may
expect aws:ec2:Instance or just ec2. Plugins should handle the standard
Pulumi format or normalize internally.
Pulumi SDK Import Path
For Analyzer development, use the correct import:
pulumirpc "github.com/pulumi/pulumi/sdk/v3/proto/go"
// NOT: github.com/pulumi/pulumi/sdk/v3/proto/go/pulumirpcMulti-Repository Ecosystem
FinFocus operates across three repositories:
- finfocus (this repo) - CLI tool, plugin host, orchestration
- finfocus-spec - Protocol buffer definitions, SDK generation
- finfocus-plugin - Plugin implementations (Kubecost, Vantage, etc.)
Cross-repo changes follow the protocol in .specify/memory/constitution.md.
Agent Skills Placement
- Tool-specific skills (
finfocus-install,finfocus-budget,finfocus-diagnose, etc.) → live inrshade/finfocusunderagent-skills/— these are product skills tightly coupled to finfocus CLI commands, file paths, and architecture - Generic cost workflow skills (
cost-check,cost-drift,cost-optimize,budget-setup) → live inrshade/agent-skillsas multi-tool skills not tied to any specific cost tool
Common Error Types
ErrNoCostData: No cost data available for a resourceErrMixedCurrencies: Multiple currencies detected in cross-provider aggregationErrInvalidGroupBy: Invalid grouping type used for time-based aggregationErrEmptyResults: Attempted aggregation on empty resultsErrInvalidDateRange: Invalid date range (end date before start date)ErrResourceValidation: Internal resource validation failedErrConfigCorrupted: Configuration file is malformed
Structured error codes for JSON/NDJSON output: PLUGIN_ERROR, VALIDATION_ERROR,
TIMEOUT_ERROR, NO_COST_DATA (see internal/engine/types.go).
Recorder Plugin
Reference plugin for inspecting Core-to-plugin data shapes and contract testing.
| Variable | Default | Description |
FINFOCUS_RECORDER_OUTPUT_DIR | ./recorded_data | Directory for recorded JSON files |
FINFOCUS_RECORDER_MOCK_RESPONSE | false | Enable randomized mock responses |
Jev Scorer Plugin
plugins/jev/ is a separate module (like plugins/kubernetes) implementing
RecommendationScorerService with TypeSafe AI's Jev API. It must not import
finfocus core packages (make check-plugin-boundaries). Design notes:
- Off unless
TYPESAFE_API_KEYis set; without it every scoring call returnsUNAUTHENTICATED. The key is read only from the environment and must never appear in logs, errors, tests or committed files. - Thin
net/httpclient inplugins/jev/internal/jevapi; no third-party Jev SDK. - Question names are
<signal>:#<position>over an ordered state list; the recommendation id never leaves the plugin (answers map back by position viabatch.indexes). Question text never contains recommendation content. Free text is stripped and capped ininternal/scoring/record.go. Tests find a record's key withquestionKey()inhelpers_test.go, because every one-recordpriorityrequest usespriority:#0. jevapi.Clientdoes not start a retry whose wait outlasts the caller's deadline (core'sscoring.timeout_seconds); it returns the*APIError.- Live tests (
TestLive*,TestEvaluationwithJEV_EVAL=1) are skipped without a key. Batching lowerspriorityrank quality (Spearman about 0.55 at batch 25 against 0.77 at batch 1), so priority is always one record per request. - Scores are ranking-only. Never gate an irreversible action on one.
Package-Specific Gotchas
Non-obvious behaviors that can cause subtle bugs if you don't know about them.
Plugin Host (internal/pluginhost/)
- Port allocation: Uses allocate→hold→release→bind pattern. Race window between
release and plugin bind is mitigated by
StartWithRetry - Zombie prevention: Always call
cmd.Wait()aftercmd.Process.Kill() PORTenv var removed: Core does NOT setPORT(avoids Cloud Run conflicts). Plugins must use--portflag orFINFOCUS_PLUGIN_PORT
CLI (internal/cli/)
analyzer servestdout: Prints ONLY the port number to stdout (Pulumi handshake protocol). ALL logging must go to stderr exclusively- DismissalStore: Uses
GetResolvedProjectDir()→ projectdismissed.json; falls back to~/.finfocus/dismissed.json config init: Without--global, inside a Pulumi project creates$PROJECT/.finfocus/config.hujson+.gitignore. Outside Pulumi project → global initconfig routes:config routes listshows effective routing source/path;config routes test <type> [region]simulates per-feature plugin selection without loading plugin binariesconfig validateand cost pre-run: both callValidateConfigSource.--fileselects a document.--output jsonprints the report. An unknown--outputis rejected before the file is read. A missing default file stays valid.cost projected,cost actual,cost recommendations,cost estimate, andcost clusterfail in pre-run when a present file is invalid, and they ignore a missing file. Flatcost.budgets.amountis warned and not applied; the on-disk field iscost.budgets.global.amount. Period stays monthly. Threshold stays 0–1000. Amount 0 disables a scope. Unknown keys warn, with a suggestion when the name is close. There is no notifications section- Unit tests leak into the real
~/.finfocus: any test that executes a mutating command (dismiss,snooze,config set) writes to the developer's and the CI runner's actual home unless it setst.Setenv("FINFOCUS_HOME", t.TempDir()).NewDismissalStore("")falls back toResolveConfigDir(), which honorsFINFOCUS_HOMEfirst. This has produced tests that pass only because a sibling test seeded the shared store — green as a package, red when run alone. Detect withHOME=$(mktemp -d) go test -run TestName ./internal/cli/; a test that fails in isolation but passes in the package is order-dependent, not flaky - Validate
--outputbefore loading state: commands that early-return on an empty result (e.g. history'slen(events) == 0) must reject an unknown format first, or an invalid--outputsilently exits 0. Seeconfig_routes.go,analyzer_check.go,plugin_list.gofor the up-front pattern - Overview docs path: the published page is
docs/src/content/docs/commands/overview.md. RootREADME.mdlinks there.docs/commands/overview.mdis not a file. Plain headers areACTUAL(MTD)andPROJECTED(PROJECTED*in state-only mode). Delta comes fromCalculateRowDelta, not projected minus month-to-date. The Warn column repeats a shown drift asdriftand also listserrorandnew.errorcovers a plugin error reported on the result (PLUGIN_ERROR,TIMEOUT_ERROR,VALIDATION_ERROR, anERROR:/VALIDATION:note) as well as a returned error;NO_COST_DATAis not an error.ApplyChangesToRowsre-derives warnings when a status changes. The TUI cell usesname+Nwhen that list does not fit in 7 columns.estimateandstaleexist onOverviewWarningand are not derived - Cost table flags:
--show-breakdownoncost projectedandcost actualadds alphabetical component sub-rows in the plain table (├─, last row└─). Empty maps, nil maps, and empty keys add no sub-rows.--show-confidenceadds the actual-cost Confidence column. Neither flag changes JSON or NDJSON.--estimate-confidencestill sets the plugin request and decides whether JSON/NDJSON keepconfidence. Either new actual flag skips the interactive TUI so the table is what the user sees. Time-based--group-bystays on the cross-provider aggregation table, which has no per-resource sub-rows - Accessibility flags are local to output commands:
overview,cost projected,cost actual, andcost recommendationsaccept--no-color,--plain,--color, and--high-contrast.overviewalso keeps--force-coloras an alias of--color. Do not put--plainon thecostparent:cost history viewalready defines a local--plain, and Cobra rejects the redefined flag.FINFOCUS_PLAIN, a non-emptyNO_COLOR,FORCE_COLOR, andFINFOCUS_HIGH_CONTRASTfill unset flags (strconv.ParseBool; invalid values are ignored). Explicit--plainor--no-colorwins over color flags. Those env vars win overFORCE_COLORandFINFOCUS_HIGH_CONTRASTwhen the color mode was not set by a flag.--plainand--no-colorstayOutputModePlain. High contrast does not changeColorOKand the other package color variables;tui.Palette(true)is ANSI 46, 226, 196, and 231, used by the styled budget box. Plain budget status text is[OK] Within budgetor[WARNING] Exceeds N% threshold. Calltui.DetectResolvedOutputModewith the resolved struct, neverDetectOutputModeFor, which re-readsNO_COLORand would undo an explicit--color.RenderScopedBudgetStatustakes the resolvedtui.Accessibilitylike the global box.cost projectedprints its diff table as plain text in every mode, so its four flags only change the budget box (the help text says so).FINFOCUS_PLAINfills incost history view's default format only: an explicit--output,--format json, orAGENT_MODEkeeps JSON, and an explicit--plainstill wins.FORCE_COLORforces color for any non-empty value except0andfalse(force-color.org; supports-color treats those two as off) - Budget CLI flags stay off the global config:
--exit-on-thresholdand--exit-codeareBudgetFlagOverrideson the command context, passed intoevaluateBudgetStatusandlegacyBudgetConfig. They are not written ontoconfig.GetGlobalConfig(). Precedence is the CLI pointer, then the scoped budget field, then parentBudgetsConfig, then the zero value. Only a copy of the global scope receives the overlay. Provider, tag, and type scopes do not.
Registry (internal/registry/)
- Region-specific binaries: When
plugin.metadata.jsonhas aregionkey, registry looks forfinfocus-plugin-<name>-<region>first, then falls back to standard names - Checksum verification: Only a confirmed hash mismatch is fatal. Missing
checksums.txt, download failures, or unlisted assets produce warnings and continue --skip-checksumflag available onplugin installandplugin update- Monorepo plugins (
tag_prefix): an entry withtag_prefix: "kubernetes-"installs fromrshade/finfocustags likekubernetes-v0.1.0. "Latest" is the highest semver among prefixed stable releases (scans 100), never/releases/latest; install dir, asset names, and recorded version use the canonical version (v0.1.0, viaCanonicalVersion). The entry also needsasset_hints.asset_prefix, and prefixes must not start withv(CLI workflows treatv*tags as CLI releases) - Asset-less releases: Release Please publishes a release before GoReleaser uploads
its archives (aws-public v0.2.0 had none for about 40 minutes). With no version
requested,
Installer.fetchReleasereplaces a latest release with zero assets by the highest-semver earlier stable release that has assets (same rule on thetag_prefixpath) and warns throughprogress. An explicit version is never swapped:FindPlatformAssetWithHintsreturns*NoAssetsError(errors.IswithErrReleaseHasNoAssets). Its message still starts withno asset found for <platform>andisNoAssetErroralso matches it witherrors.Is, so the CLI's version fallback (prompt or--fallback-to-latest) still applies. Assets that exist but do not match keepno asset found for ... Available:.make test-e2e-kindpinsE2E_AWS_PUBLIC_VERSION(Renovate bumps it via the# renovate:comment regex manager) - Default plugin dir:
DefaultPluginDir()isconfig.ResolveConfigDir()/plugins(FINFOCUS_HOME, PULUMI_HOME/finfocus, ~/.finfocus), the directory discovery reads.NewInstaller("")andNewInstallerWithClient(c, "")use it
Router (internal/router/)
- Fallback chain:
$0.00cost is a VALID result (does NOT trigger fallback). Only nil/empty results trigger fallback to the next plugin - Priority: Higher number = higher priority (sorted descending by
sortByPriority) - Provider is the billing cloud, not the package:
resourcetype.NormalizeProviderholds the only alias table (aws-native→aws;azure-native,azurerm→azure;google-native,google→gcp; anything else passes through lowercased).resourcetype.ExtractProviderreturns the cloud andExtractPackagethe raw prefix. Never split a type token for a provider anywhere else.resource_typekeeps the package, so routingpatternssuch asaws-native:*still match.ProviderMatchesnormalizes both sides, so a plugin that still listsazure-nativekeeps matching. Provider budget keys,ByProvider,GroupByProvider, theprovider=filter and history provider lookups compare normalized names, which also lets history entries stored under a package name match a cloud filter - No config = no routing:
createRouterForEngine()returns nil if no routing config; engine falls back to querying all plugins
Engine (internal/engine/)
hoursPerMonth = 730for monthly cost calculations- Plugin error text is kept: a failed
GetProjectedCostorGetActualCostcall keeps the plugin's gRPC status as<Code>: <message>(pluginRPCError, which still answersstatus.Code), e.g.plugin call failed: InvalidArgument: region is required for GetProjectedCostin.finfocus.errors. Only an empty projected result list isno cost data available. The projectedNO_COST_DATAnote appends the first other error after any decline reasons, and the actual--fallback-estimatenote isERROR:plus that error, both capped at 160 bytes. Core does not readaws:regionfrom Pulumi provider or stack config; region comes fromregion,availabilityZone, an ARN, thenAWS_REGION/AWS_DEFAULT_REGION - Projected cost diff:
cost projectedcallsGetProjectedCostDiff. An empty operation is a create ($0before, current price after); Terraform state maps tosame(existing infrastructure, no delta). Internalpulumi:types that no plugin priced are left out of the entries, and a projected cache hit is re-keyed to the requesting resource's ID (identical resources share one cache entry).update,replace, andcreate-replacementpriceOldPropertiesthenProperties.deleteanddelete-replacedprice old properties and a$0after.sameis priced once. Both sides use the same basis:OldPropertiesis outputs merged under the old inputs (likeProperties), andref.*tags are resolved once over the whole plan (resolveDiffRefTags) and given to both descriptors, because the before and after slices hold different resources. A replacement'screate-replacement,replace, anddelete-replacedsteps share a URN and are collapsed into oneupdateentry first (collapseReplacements), or the old resource would be counted twice.summary.totalMonthlyand budget evaluation use the after total. Table output is the diff table (TTY included). JSON addsfinfocus.diff. NDJSON is one diff entry per line.--show-breakdownadds component sub-rows on that table only. Recommendations are merged onto the after cost and skipped for deletes - Cost history (
cost history collect|view|list): snapshots live in~/.finfocus/history/<project>@<stack>.history.db(@cannot appear in a Pulumi name, so names never collide). The project is thePulumi.yamlin the working directory or the middle part of--stack org/project/stack(resolveHistoryTarget). A database records its project inmetaandOpenCostDBForerrors on a different one. A legacy<stack>.history.db(slashes become dashes) is kept by the project its snapshot URNs name (CostDB.InferProject), or adopted when they name none; any other project gets its own file. With no project, a bare--stackuses the legacy file, else a single@match, else errors. That file is not the resource-observationhistory.db.collectprices each successfulupdatethroughGetProjectedCostWithErrorsand stores the result; a successfuldestroyis$0with annotationStack destroyedand does not call the pricer.viewandlistare read-only. A real plugin$0is stored. Adapternone, the unpriced note, or a result error fails that checkpoint (fail fast, per the #549 design: no inaccurate totals), and that includes a type an installed plugin declines.pulumi:internal types (provider resources arecustom: true) are skipped before pricing, because the engine never prices them.internal/historymust not importengineoringest(enginealready importshistory). The parentcost --stackflag is reused; history subcommands do not redeclare it - Cost history collect details:
pulumiExporter.Historyreadspulumi stack historypage by page (page size 100), stops on a page with no new versions (a short page is not an end marker), and asks once without paging flags if the CLI rejects them, because the default page is 10 updates.importandrefreshupdates are not collected (a checkpoint is a deployment; their cost shows at the next update).history listskips an unreadable or locked database with a stderr warning (ListCostDBsLenient), andStatsreads only the key count and the two end snapshots.view --providererrors on an unknown provider. - Cost history currencies:
cost history viewwarns and keeps the dominant currency (most snapshots; a tie keeps the newer timestamp, then the earlier code).--currencyfilters and does not warn.--strictreturnshistory.ErrMixedCurrencies. An empty currency is(unset). One currency produces no warning.cost history exportuses the same default and prints the warning on stderr - Cost history prune:
cost history prunedeletes per-stack snapshots (--keep,--older-than,--force).--dry-runis the global ax flag. Compaction usesbolt.Compactafter the database is closed. This is notBoltStore.cleanupExpiredEntries.cost.history.retention.auto_pruneruns that policy aftercollectwhen the command loaded config - Cost history export:
cost history exportwrites JSON, CSV, or NDJSON from the per-stack database.--formatis the root ax flag. The command does not declare a second--format, because Cobra rejects the redefined flag.csvandndjsonare not agent modes (ParseModeallowsjsonandhumanonly). The export command'sArgssaves those two values and sets the flag tojsonbeforeax.Executeresolves the mode. Other commands still reject them.--fromand--toare inclusive dates.--providerkeeps every snapshot and setstotal_monthlyto that provider, or 0 when the snapshot has none. Sparklines arehistory.Sparkline(U+2581 through U+2588, width 7). A flat series is the low block. Empty input is an empty string.cost projectedandcost actualadd a Trend column only when that stack's history file exists. A missing file does not fail the cost command. There is no ntcharts dependency. The interactivedkey from #550 is not part of this command - Cost history diff:
cost history diffcompares two stored snapshots by URN (internal/history/diff.go). It reads bbolt only. A cost move of $0.01 or less is unchanged.--thresholdhides smaller impacts.--fromand--totakevNorYYYY-MM-DD(nearest snapshot). Empty--tois the newest snapshot. The interactivedkey from #550 is not part of this command - Cost history in CI:
cost history collect --versionsdefaults to 0 (every successful checkpoint not already stored).--versions 1keeps the newest. Recipes aredocs/src/content/docs/guides/ci-cd-cost-tracking.md. There is nodocs/guides/ci-cd-cost-tracking.mdpage. Release assets are versioned archives (finfocus-v0.4.0-linux-amd64.tar.gz); the install script isscripts/install.sh cost projected --explaincallsGetPricingSpecafterGetProjectedCostDiffand stores the view onDiffEntry.PricingSpec(pricing_specin JSON and NDJSON). It does not changeMonthly. The default is off, and a disabled run does not call the RPC. A delete is explained from the old properties; every other operation uses the new ones. An RPC error or an empty spec omits the field and keeps the cost. The next selected plugin is tried when the first has no spec. Unpricedpulumi:rows are not explained because they are not diff entries- Plugin pricing spec fallback is off by default.
newEngineWithCachecopiescost.pricing_spec_fallback.cost projected --pricing-spec-fallbackoverrides that for the command when the flag is set. When on, a resource whose plugins returned no projected price is priced fromGetPricingSpecbefore local YAML. Disabled runs do not call the RPC. Notes start withCalculated from plugin pricing specand the adapter isplugin-spec. A$0rate is a priced result. Unknown billing modes and RPC errors fall through to YAML. EachGetPricingSpeccall (fallback andDiscoverPricingSpec) has a 5s deadline (perResourceTimeout). A chain that stopped at a plugin whose routerFallbackis false asks no plugin for a spec. With the flag on, projected cache keys end in/pricing-spec, so a run with it off never reads aplugin-specresult (the exportedProjectedResourceCacheKeystays the default key).per_hourandper_cpu_houruse 730 hours (the AWS Pricing Calculator basis, 365 × 24 / 12),per_dayusesdaysPerMonth(30, the month AWS's billing examples use: the ELB page's$/hour * 24 hours * 30 daysand CloudWatch's30 days * 24 hours = 720 hours). Do not "fix" the 720 against 730 by arithmetic: both are AWS's own conventions for different purposes.per_gb_monthmultiplies by storage size or 1 GB. A billing mode the engine does not know that still has a usable unit, such asper_hour_plus_data, is priced from the unit alone and the note says<mode>: hourly rate only, other charges not included. A tiered spec is graduated, as finfocus-spec defines it (docs/ADVANCED_PATTERNS.md: usage in each tier ismin(usage, max) - min; the S3 example is "first 50 TB at $0.023, next 400 TB at $0.022"): each tier bills the part of the quantity inside it (graduatedTierCost). Tiers whose ranges do not cover the whole quantity (a gap, a first tier above zero, a bounded last tier below the quantity) are unusable and fall through, since the uncovered part has no rate. A$0rate stays a price, so a plugin must answerzero_costor an error for "no price", not a zero rate (#1639 reports aws-public returning a zeroper_hourrate for a type it does not find, which core prices as$0; unverified here, since it is a plugin-side issue) - Estimate TUI pricing discovery calls
GetPricingSpecwhencost estimate --interactivestarts.DiscoverPricingSpeccaches by resource type, SKU, and region on the engine for that session, so an edited SKU asks the plugin again. The view lists each plugin billing mode, its tiers, assumptions, and usage hints. Left and right move between modes.not_implemented, an empty mode, and RPC errors hide that section and leave property editing in place. The lookup does not replaceEstimateCost - Budget health thresholds: OK (<80%), WARNING (80-89%), CRITICAL (90-100%), EXCEEDED (>100%). Aggregation uses worst-case status
- Cache hits: Append
(cached), including the leading space, to the Adapter field for visual feedback - Cache corruption: Auto-detected and auto-recovered (delete + recreate)
- Plugin TTL hints: Plugins can set
expires_aton responses to control per-entry cache TTL. The engine extractsExpiresAtfromCostResult, callscache.CalculatePluginTTL(), and usesSetWithTTL()when a plugin hint is present. Past timestamps skip caching entirely. TTLs exceedingMaxTTLSeconds(604800 = 7 days) are capped. Debug logs record TTL overrides; warn logs record caps and skips - Optional LRU tier:
cost.cache.lru_enabled(default false) wraps the BoltDB cache withcache.TieredStoreinsideinitCacheFromConfig, so everynewEngineWithCachecaller gets it. Reads hit memory first and promote a disk hit. Writes update disk, then refresh memory. Expired memory entries fall through.lru_max_itemsof 0 uses 256.FINFOCUS_CACHE_LRU_ENABLEDandFINFOCUS_CACHE_LRU_MAX_ITEMSoverride the file. A wrap failure keeps the Bolt store. The engine field stayscache.Cache checkPluginSupportssends the descriptorproto.PrepareProjectedDescriptorbuilds (the same oneGetProjectedCostsends, including a region inherited from a referenced resource, and its attributes), and caches per client+provider+type+region+sku+feature, plus an attributes digest when the resource has attributes (SKU is part of the key: a first SKU-less resource in a region must not poison the cached answer for every other SKU there); plugins on finfocus-spec ≥ v0.6.2 answerSupportsfor real, so a region-bound plugin (aws-public) declines other regions instead of being called and failing. A plugin that never implementsSupportsProvidergets the SDK's generic fallback response (Supported:false,Reason: pluginsdk.DefaultSupportsNotImplementedReason); the engine treats that reason as fail-open (cachedtrue), same as an RPC error, so such a plugin isn't silently dropped from routing- Recommendations:
convertProtoRecommendationkeeps the full plugin record (ID, category, priority, confidence, source, metadata,ImpactDetail,ResourceInfo,ActionDetail, primary/secondary reasons);Recommendation.IDis the dismissal ID. The cache key isrecommendations/multi/{types}/{hash}where the hash covers resource id/provider/type/ properties plus dismissed IDs (cache.HashRecommendationInputs).--include-dismissedsetsinclude_dismissedon the plugin request and still sends the host's excluded IDs, so an older plugin keeps hiding host dismissals. That fetch suffixes the cache key with/include-dismissed. The default key is unchanged. Spec:specs/622-include-dismissed/and finfocus-specspecs/599-include-dismissed/. Resources are routed per plugin viarouteRecommendationTargets(router featureRecommendations) - Recommendation scoring (
internal/scoring, opt-in viascoring.*config, off by default):scoring.Service.Scoreruns after the fetch incost recommendations, sends recommendations to a scorer plugin (PLUGIN_CAPABILITY_RECOMMENDATION_SCORING, normalizedrecommendation_scoring) throughpbc.RecommendationScorerServiceClient. Core appliesidentifier_mode(default pseudonymized: per-request HMAC key, opaquerec-Nids, raw ids scrubbed from text) andfield_allowlistbefore sending; identifier handling also covers identifiers insideaction_detail(Kubernetes cluster/namespace/controller/container names) and free text there; the first call probes batch size (20, halving on INVALID_ARGUMENT), later batches run up to 8 concurrent. Scorer failure only warns. Scores are cached in thescoresbucket (extracted values only). Scores never dismiss or hide anything. Scorer-only plugins are skipped byrouteRecommendationTargets. Cost features (ProjectedCosts,ActualCosts,BatchCost) drop scorer-only clients insideselectPluginMatchesForResourcebeforeSupports, including router matches, so they never appear in unpriced decline notes. State-based actual-cost estimation uses the same skip beforeGetProjectedCost. Plugins with no capabilities, and plugins that also reportrecommendations, stay offered. Recommendations selection is unchanged
Overview Field Semantics (internal/engine/overview_*.go)
Understanding what each field means prevents the most common overview bugs.
Every field on OverviewRow has a specific temporal basis, population rule,
and set of valid comparisons. Violating these invariants produces subtle bugs
(misleading deltas, nonsensical drift, UI garbage).
Cost Fields — Temporal Basis
| Field | Struct | Temporal Basis | Unit | Source |
MTDCost | ActualCostData | Partial month (day 1 → today) | Dollars spent so far | Actual cost plugin |
MonthlyCost | ProjectedCostData | Full canonical month (730h) | Dollars if run all month | Projected cost plugin |
ExtrapolatedMonthly | CostDriftData | Full calendar month (28-31d) | Projected from MTD trend | Calculated by CalculateCostDrift |
Delta | CostDriftData | Full calendar month | ExtrapolatedMonthly - Projected | Calculated by CalculateCostDrift |
Key rule: MTDCost and MonthlyCost are different units. You cannot
subtract one from the other. To compare them, you must first extrapolate
MTDCost to a full month using getExtrapolatedActual() (30-day standard)
or CalculateCostDrift() (calendar-accurate).
When Fields Are Nil vs Populated
Fields start nil after merge and get populated during enrichment. What gets
populated depends on the resource's Status:
| Status | ActualCost | ProjectedCost | CostDrift | PropertyDiffs |
| Active | Yes (has billing history) | Yes (current config) | Maybe (nil if < 10% or day < 3) | No (no changes) |
| Updating | Yes (still running) | Yes (new config pricing) | Maybe | Yes (what changed) |
| Replacing | Yes (old resource billing) | Yes (new resource pricing) | Maybe | Yes (what changed) |
| Creating | No (doesn't exist yet) | Yes (new resource pricing) | No (no history) | No |
| Deleting | Yes (still running) | No (will be removed) | No (no projection) | No |
This table is the source of truth for which cost computations are valid per status. If a formula assumes a field is non-nil, check this table first.
Delta Column — What It Means Per Status
The "Delta" TUI column answers: "how will this change affect my monthly bill?"
Use CalculateRowDelta() — it encodes status-aware logic:
| Status | Delta Formula | Meaning |
| Updating/Replacing | projected - extrapolatedActual | Cost impact of the config change |
| Creating | +projected | New cost being added |
| Deleting | -extrapolatedActual | Cost being removed |
| Active (with drift) | CostDrift.Delta | How much actual spend deviates from projection |
| Active (no drift) | - (no delta shown) | Spend is tracking projection (< 10% off) |
Extrapolation — Two Methods, Intentionally Different
| Function | Month Basis | Used For |
getExtrapolatedActual() | 30-day standard | Delta calculations (consistent cross-month) |
CalculateCostDrift() | Calendar days (28-31) | Drift % (calendar-accurate precision) |
Do not unify these. Delta uses 30-day for stable comparisons across months. Drift uses calendar days because a February drift % must account for 28 days.
Drift Nil Cases
CostDrift is nil (not populated) in these cases — all intentional:
- Day 1-2 of month (
driftMinDay = 3): insufficient data - Drift < 10% (
driftWarningThreshold): not significant enough to show - New resource (has projected, no actual): nothing to extrapolate from
- Deleted resource (has actual, no projected): nothing to compare against
- Recently created (
CreatedAtwithin billing window, < 3 days old)
Code must always handle row.CostDrift == nil as a normal case, not an error.
Pulumi Plan Data — What to Filter
PulumiStep.OldState.Inputs and NewState.Inputs contain both user-specified
properties and Pulumi internal metadata. When displaying to users:
- Filter keys prefixed with
__(e.g.,__defaults,__provider) — these are Pulumi SDK internals, not user properties - Truncate values in TUI to prevent wrapping (max 40 chars via
truncateDiffValue()) — Pulumi inputs can contain large arrays/objects - PropertyDiff data flow: Plan JSON →
diffInputs()(CLI) →PlanStep.PropertyDiffs→ merge →OverviewRow.PropertyDiffs→ TUI view
State-Only Mode
When no preview is provided, overview shows state resources with * footnote
on projected costs. The p key triggers on-demand preview; when it completes,
ApplyChangesToRows() and ApplyPropertyDiffsToRows() update rows in-place.
Cluster allocation (internal/engine/cluster*.go, plugins/kubernetes/)
- Core never interprets Kubernetes: nodes arrive from
GetStatsas ordinaryResourceDescriptors (sku/regionpassed as properties) and are priced byGetProjectedCostWithErrors; grouping is string-map aggregation - Node identity (#1588): the allocator keys a node by cluster and node
name joined with NUL, same as the workload key. The priceable
idstays the Kubernetes node name so stats validation and the idle row still match it.NodeDescriptorcopies the kubeconfig context onto tagsclusterandnode. A priced node with noclustertag still joins on the node name. Two priced entries that sharekind=nodeandidare rejected by the SDK before allocation; a multi-cluster request gives each one its own id and keeps the Kubernetes name on thenodetag $0price = unpriced: aws-public returns$0(not an error) for unknown instance types, sopriceResourcestreatsMonthly <= 0as unpriced- Conservation is enforced in core (
VerifyConservation, rel 1e-6, delegating topluginsdk.CheckConservation) even though the conformance suite also checks it — third-party allocators exist, and one shared SDK rule keeps core and plugins in agreement plugins/kubernetesis a nested module and must not import core packages (make check-plugin-boundaries); it declinesSupportssocost projectedskips it (finfocus-spec ≥ v0.6.2 delivers pluginSupportsanswers to hosts; earlier SDKs errored and the engine failed open)- Allocator policy v2 (
specs/614-allocator-policy-v2/):idleandsystem_workloadsacceptshareas well as the defaultseparate. Idle CPU and memory are shared in proportion to each workload's already-computed CPU cost and memory cost. System rows (namespace=kube-systemorcontroller_kind=DaemonSet) are then folded into the other workloads on the same node. The idle row stays even at$0, becauseValidateAllocateResponserequires exactly one idle row per priced node. When both fields areshare, idle is distributed first (including onto system rows) and system rows are folded after that - EKS Fargate pods (
specs/615-eks-fargate-pods/): a node labeledeks.amazonaws.com/compute-type=fargatestill has no capacity rows and no node descriptor. Each running pod on it is a priceableaws:eks/fargate:Pod(skufargate, tagskind=fargate,cpu,memory_gib). The allocator assigns that priced cost to the pod and never folds it into__idle__.Monthly <= 0stays unpriced (Fargate pod has no price, or the pricer's note). Afargate-node name with no fargate priced entry still notesFargate pricing not supported yet. Rates are aws-public's job (finfocus-plugin-aws-public#409); kind cannot simulate Fargate, somake test-e2e-kinddoes not cover it - Projected workload pricing (
specs/621-k8s-workload-projected-cost/):plugins/kubernetes/workloadprices Deployment, StatefulSet, DaemonSet, Job, and CronJob fromattributesat rates fromFINFOCUS_KUBERNETES_CPU_HOURLY_RATEandFINFOCUS_KUBERNETES_MEMORY_GIB_HOURLY_RATE, withFINFOCUS_KUBERNETES_DAEMONSET_NODE_COUNTandFINFOCUS_KUBERNETES_JOB_HOURS_PER_MONTHas hints.SupportsandGetProjectedCostshareworkload.Estimate. ASupportsdecline reason (at most 160 characters) is kept in aNO_COST_DATAnote, like aGetProjectedCosterror's text (see Engine). The per-pod request reusesusage.EffectiveRequests, with limits standing in for absent requests first. Prices carryexpires_at= now because the core cache key cannot see the plugin's environment; without it a rate change kept the old cached price - Pulumi URN linking (
specs/616-k8s-pulumi-urn-linking/): the provider does not write a URN onto objects. Users set annotationfinfocus.dev/pulumi-urn(not a label: URN values contain:and exceed 63 characters). The collector copies it to subjectlabel.finfocus.dev/pulumi-urn, which stats validation allows.cost cluster --group-by pulumi-stackgroups by<stack>/<project>; a missing or malformed value is<none>. Group JSON includespulumi_urns
MCP Server (internal/cli/mcp.go, internal/cli/output_mode.go)
- Per-call lifecycle: ax-go's dispatcher re-executes the shared root once
per
tools/call(nestedExecuteContext), so rootPersistentPreRunE/PersistentPostRunErun per call.commandLifecycle.servingmarks dispatched calls: they reuse the server'sloggingSessionviaattachand never close it. Opening/closing logging per call previously leaked handles and ended inclose .../finfocus.log: file already closed.loggingSession.Closeis idempotent. Config resolution still runs per call - Serialized dispatch: one mutex covers every call, so a blocking command
stalls the whole server. That is why
analyzer serveis excluded - Output resolver:
resolveOutputFormatgives an explicitly set--outputfirst priority, then--format(the dispatcher injectsjsonon every call), thenAGENT_MODE, resolved viaax.ResolveMode(..., stdoutIsTTY=true), else the flag default. It deliberately ignoresax.ModeFromContextand TTY detection: those report JSON whenever stdout is piped, which would flip redirected human output. New commands with an output flag must call it, and commands without one should emit JSON whenmachineOutputRequested(cmd) - Flag stickiness: the dispatcher resets flag values and
Changedper call, but only on a real server. NestedExecuteContextin unit tests does not reset, so assert cross-call--outputbehavior in the integration test - Exclusion:
applyMCPExclusionsmarksmcpExcludedCommands(root,analyzer serve,cost history collect(minutes-long, would stall the serialized dispatcher),setup,plugin init) with ax-go's node-onlymcp.Excludeat tree build time; they stay in--help. ax-go (v0.7.0+) skipshelpand non-runnable groups itself. Never useHiddento exclude a root/group: ax-go prunes the whole subtree.withPositionalCommandsHiddenstill hides positional-arg leaves while an MCP tool list is built so the static__schema --as=mcpmatches the live server, which cannot pass positional args - Tool allow-list golden:
internal/cli/testdata/mcp/tools.goldenpins the tool list for both the static schema (unit) and livetools/listof both entry points (test/integration/mcp_server_test.go). A new command must make an expose-or-exclude decision; regenerate withUPDATE_GOLDEN=1 - Version: the MCP handshake rejects
dev/unknownversions, so binaries built for MCP tests need-ldflags -X .../pkg/version.version=...
Plugin Upgrade (internal/pluginupgrade/, agent-skills/finfocus-plugin-upgrade/)
- Bumping finfocus-spec in core needs a hop:
TestHopsReachCoreSpecVersionfails untilhops.gohas an entry whoseTois at leastpluginsdk.SpecVersion, andTestHopsMatchGuidesrequires a matchingreferences/to-vX.Y.Z.md. Add both in the bump PR, even for an additive release (a guide that says "no changes required" is fine) - Nested modules must match the root finfocus-spec pin: CI validation
compares
go.modwithplugins/kubernetes/go.modandplugins/jev/go.modand fails whengithub.com/rshade/finfocus-specdiffers. A root pin bump updates both modules even when they do not use the new field.pluginsdk.SpecVersionstays put until a release moves it, so a pseudo-version pin does not add a hop - Hops are releases that need author action, not minor lines: v0.5.7 (a
patch) changed
HandleDryRun; v0.6.1 raised Go to 1.27.1 SpecVersionmust bev-prefixed:pluginsdk.ValidateSpecVersionrejects"0.6.1", soGetPluginInforeturnsInternalandplugin listshowsN/A.plugin initnow writesSpecVersion = pluginsdk.SpecVersion; scaffolds from v0.4.0 and earlier have a bare literal, which the upgrade rewrites- Minimum supported version is v0.5.0; there are no pre-rename plugins
- The scaffold's finfocus-spec pin is
pluginsdk.SpecVersion(#248), so bumping finfocus-spec in core also moves new plugins.TestPluginInitTracksCoreSpecVersionkeeps it at v0.7.1 or newer and checks that a fresh scaffold needs noplugin upgrade; the scaffold integration test proves the templates still compile against it plugin.manifest.jsonis not the pluginsdk manifest:plugin validateparses it as the flatregistry.Manifest(name,version, ...) and requires both to match the install directory. The scaffold'smanifest.json(pluginsdk.SaveManifest, nestedmetadata/specification) fails to parse there, so the generatedmake installwrites the flat file withprintf.test/integration/plugin/scaffold_build_test.gobuilds, installs, and validates a generated project- Rebuild
agent-skills/finfocus-plugin-upgrade/finfocus-plugin-upgrade.skill(a zip ofSKILL.md+references/) after editing either - Skill install (
internal/pluginskill/):plugin initandplugin upgraderunnpx -y skills@1.7.0 add <finfocus tree URL> --skill finfocus-plugin-dev --skill finfocus-plugin-upgrade --agent codex --agent claude-code --copy -yin an empty temp directory, then copies the two skill directories into the plugin and merges theirskills-lock.jsonentries. Never run npx in the plugin directory: npx honors its.npmrc(registry) andnode_modules(localskillspackage), so an untrusted checkout could run its own code. The copy and the lockfile merge write through anos.Rooton the plugin directory, so a symlinked.agents,.claude, orskills-lock.jsoncannot redirect a write outside the checkout. Without--agentthe skills CLI writes a copy for every agent it detects (.bob,.grok, ...). The source is the release tag only for a clean semver newer than v0.4.0 (the last tag without the skill), elsemain. Upgrade re-runsadd, notskills update, becauseupdatemoves tomain. Every failure is a warning, never an error. Tests must never run npx:internal/cliswaps the installer inTestMain(main_test.go,export_test.go), andtest/integration/pluginpasses--no-skill. Spec:specs/620-plugin-dev-skill/
Integration Tests (test/integration/)
- The CLI helper must go through
ax.Execute:helpers.CLIHelper.Executeruns commands viaax.Execute, the same entry point ascmd/finfocus. Callingcli.NewRootCmd().Execute()directly does NOT mount the persistent agentic flags (--format,--dry-run,--yes,--idempotency-key), so those flags fail with "unknown flag" in integration tests while working in production and in unit tests (which useaxtest.Run).ax.Executereturns an exit code rather than an error, so the helper converts non-zero codes back into an error from stderr - Many integration tests do not isolate
HOME: tests that callhelpers.NewCLIHelper(t)withoutWithEnvread the developer's real~/.finfocus/config.hujson, so local config can change their results. (A localcost.budgetsentry used to inject a "BUDGET STATUS" banner into JSON/NDJSON output and fail ~57 tests locally; the banner now renders only for table output.) Always diff the integration failure set against a pre-change baseline rather than comparing failure counts - Overriding
HOMEfor ago/makechild moves Go's caches: whenGOPATHis not exported (CI),HOME=<t.TempDir()>puts the module cache under the temp dir. Its files are read-only, sot.TempDircleanup fails withpermission denied(green locally whereGOPATHis set). Pass the realGOMODCACHE/GOCACHEfromgo env, asscaffold_build_test.godoes. Reproduce withenv -u GOPATH go test ... config.yamlfixtures are intentional: mostconfig.yamlreferences intest/integration/write legacy YAML as input to exercise auto-migration. Only assertions thatconfig initcreates a file should expectconfig.hujson
Recent Changes
- 622-include-dismissed:
cost recommendations --include-dismissedsetsGetRecommendationsRequest.include_dismissed(finfocus-spec field 8) and still sends excluded IDs; the cache key gains/include-dismissed - 621-k8s-workload-projected-cost: finfocus-spec v0.7.3 (
ResourceDescriptor.attributes); core sends redacted attributes; the kubernetes plugin prices declared workloads - 608-batch-cost-consumer: Added Go 1.27.1 (see
go.mod) + finfocus-spec v0.6.0 (proto definitions withBatchCostRPC), Cobra (CLI), gRPC, zerolog (logging) - 608-resource-history-store: Added Go 1.27.1 (see
go.mod) + BoltDB (go.etcd.io/bbolt— already ingo.mod). - 608-estimate-cost-rpc: Added Go 1.27.1 (see
go.mod) + finfocus-spec v0.6.0 (proto definitions), gRPC, Cobra, zerolog - 607-state-only-flag: Added Go 1.27.1 (see
go.mod) + Cobra (CLI framework), Bubble Tea (TUI), zerolog (logging) - 606-cache-expires-at: Added Go 1.27.1 (see
go.mod) + finfocus-spec v0.6.0 (providesexpires_atproto fields), BoltDB (cache storage), zerolog (logging)
Active Technologies
- Go 1.27.1 (see
go.mod) + finfocus-spec v0.6.0 (proto definitions withBatchCostRPC), Cobra (CLI), gRPC, zerolog (logging) (608-batch-cost-consumer) - BoltDB cost cache (
~/.finfocus/cache/cache.db) —Engine.GetProjectedCostcaches batch projected results per-resource viastoreProjectedCostCache;Engine.GetActualCostWithOptionscaches actual-cost results by full request key viastoreActualCostCacheIfClean(608-batch-cost-consumer) - Go 1.27.1 (see
go.mod) + BoltDB (go.etcd.io/bbolt— already ingo.mod) (608-resource-history-store) - BoltDB at
~/.finfocus/history/history.db(separate from cache) (608-resource-history-store) - Go 1.27.1 (see
go.mod) + finfocus-spec v0.6.0 (proto definitions), gRPC, Cobra, zerolog (608-estimate-cost-rpc) - N/A (no new persistent state) (608-estimate-cost-rpc)
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

