# Comprehensive Finance Consultant Agent Skill

> A Claude skill from dungnotnull/comprehensive-finance-consultant-agent-skill.

- **Type:** Skill
- **Install:** `agentstack add skill-dungnotnull-comprehensive-finance-consultant-agent-skill-comprehensive-finance-consultant-agent-skill`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [dungnotnull](https://agentstack.voostack.com/s/dungnotnull)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [dungnotnull](https://github.com/dungnotnull)
- **Source:** https://github.com/dungnotnull/comprehensive-finance-consultant-agent-skill

## Install

```sh
agentstack add skill-dungnotnull-comprehensive-finance-consultant-agent-skill-comprehensive-finance-consultant-agent-skill
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# SKILL.md — Finance Consultant Skill Registry

> The canonical registry and contract documentation for the **Finance Consultant** skill.
> This file describes how skills/agents/tools/hooks are registered, resolved,
> executed, and validated, including input/output JSON schemas.

---

## 1. Identity

| Field | Value |
| --- | --- |
| Skill name | `finance-consultant` |
| Version | `1.1.0` |
| Language | TypeScript (ESM, Node.js >= 18) |
| Runtime dependencies | `zod` only |\n| Research grounding | 29 applied papers (`RESEARCH-PAPER-KNOWLEDGE-BRAIN.md`) |
| Entry point | `dist/registry/index.js` (`buildSkill`) |
| LLM provider | OpenAI-compatible (provider-agnostic with failover) |

## 2. Architecture summary

A **modular skill-registry pattern** with a **chain-of-thought router** orchestrating
**specialized sub-advisor agents** over a **deterministic financial tool layer**,
all wired together by an **execution engine** and instrumented with a **hook
lifecycle**.

```
ConsultationRequest
      |
  ConsultationEngine ──(hooks)──> HookRegistry / EventEmitter
      |
  Orchestrator (router: CoT-LLM → keyword fallback)
      |  selects 1..6 advisor categories
  Sub-Advisors (6)
   |  each: compute deterministic baseline metrics (tools)
   |  each: LLM call (JSON mode) → parse → validate → graceful fallback
  Orchestrator.aggregate (prioritize, headline, disclaimers)
      |
  FinanceConsultation (Zod-validated)
```

See `assets/system-architecture.md` for the full diagram and module map.

## 3. Registration

### 3.1 Agents (`SkillAgentRegistry`)
Agents register via `SkillAgentRegistry.register(agent)` or `registerAll([...])`.
There is exactly one **orchestrator** and six **advisors**.

| Agent id | Kind | Category | Allowed tools |
| --- | --- | --- | --- |
| `orchestrator` | orchestrator | — | — (routing only) |
| `budget-cashflow-advisor` | advisor | `budget-cashflow` | cashflow-analyzer, budget-allocation, net-worth-calculator |
| `debt-management-advisor` | advisor | `debt-management` | debt-payoff-strategist, amortization-calculator, payoff-time-estimator |
| `investing-advisor` | advisor | `investing` | asset-allocation-recommender, compound-interest-calculator, net-worth-calculator |
| `retirement-tax-advisor` | advisor | `retirement-tax` | retirement-projection, tax-estimator, compound-interest-calculator |
| `insurance-risk-advisor` | advisor | `insurance-risk` | insurance-coverage-evaluator, net-worth-calculator |
| `goal-planning-advisor` | advisor | `goal-planning` | savings-goal-projection, emergency-fund-calculator, compound-interest-calculator |

Registry self-check (`agents.validate()`) enforces: exactly one orchestrator, all
six categories covered, no duplicate ids, advisor ids match the `category→id` map.

### 3.2 Tools (`ToolRegistry`)
13 financial tools. Each declares `inputSchema`/`outputSchema` (JSON Schema) and a
`category`. Tools are **deterministic** and **cacheable**. Execution validates input
**and** output against the schemas; invalid outputs are rejected as execution errors.

| Tool | Category | Description |
| --- | --- | --- |
| `net-worth-calculator` | balance-sheet | assets, liabilities, net worth, liquid net worth |
| `cashflow-analyzer` | budget-cashflow | monthly income, expenses, net cash flow, savings rate |
| `emergency-fund-calculator` | savings | months covered, shortfall, status |
| `debt-payoff-strategist` | debt-management | snowball vs avalanche simulation |
| `amortization-calculator` | debt-management | payment, schedule, total interest |
| `payoff-time-estimator` | debt-management | single-balance time + interest |
| `compound-interest-calculator` | investing | FV of PV + contributions |
| `retirement-projection` | retirement-tax | nest egg + safe-withdrawal income |
| `savings-goal-projection` | goal-planning | on-track + required contribution |
| `asset-allocation-recommender` | investing | stocks/bonds/cash/alts by risk |
| `tax-estimator` | retirement-tax | simplified bracket estimate |
| `insurance-coverage-evaluator` | insurance-risk | coverage gaps |
| `budget-allocation` | budget-cashflow | 50/30/20 split |

### 3.3 Hooks (`HookRegistry`)
Lifecycle hooks fire at well-defined stages. Built-ins: audit log, metrics, state
sync, and typed event emission. Any failure is isolated and reported to `error`
hooks without aborting the consultation.

Stages: `consultation.before`, `consultation.after`, `router.before`, `router.after`,
`advisor.before`, `advisor.after`, `tool.before`, `tool.after`, `llm.before`,
`llm.after`, `context.compressed`, `error`.

## 4. Resolution & execution

1. Host calls `buildSkill(opts)` → composition root wires runtime + tools + hooks +
   agents + engine and runs `agents.validate()`.
2. Host calls `skill.consult(ConsultationRequest)` → `ConsultationEngine`.
3. Engine fires `consultation.before`, then `orchestrator.route(...)`:
   - explicit `focusAreas` → used directly (confidence 1.0)
   - else CoT LLM routing (constrained to the 6 categories, JSON)
   - else deterministic keyword heuristic
4. Engine resolves each selected category to its advisor and runs them
   (sequential, or bounded-parallel via `enableSubAdvisorParallelism`).
5. Each advisor (`runAdvisor`):
   - computes deterministic baseline metrics via allowed tools,
   - builds its system prompt with profile summary + metrics,
   - context-budgets the messages through `ContextManager`,
   - calls the LLM in JSON mode, parses + normalizes,
   - on **any** failure, synthesizes a deterministic fallback `AdvisorOutput`,
   - force-merges validated metrics so numbers are never hallucinated,
   - validates the final output against `AdvisorOutputSchema`.
6. `orchestrator.aggregate(...)` produces a prioritized `FinanceConsultation`,
   validated against `FinanceConsultationSchema`.
7. Engine fires `consultation.after`.

## 5. Input / output JSON schemas

### 5.1 Input — `ConsultationRequest`
```jsonc
{
  "query": "string (required, minLength 1)",
  "profile": "FinancialProfile (required)",
  "focusAreas": ["budget-cashflow" | "debt-management" | "investing" | "retirement-tax" | "insurance-risk" | "goal-planning"] // optional
}
```
Full schema: `assets/schemas/consultation-request.schema.json` and `financial-profile.schema.json`.

### 5.2 Output — `FinanceConsultation`
```jsonc
{
  "headlineSummary": "string",
  "riskToleranceAssessed": "conservative" | "moderate" | "aggressive",
  "advisorOutputs": [
    {
      "advisorId": "string",
      "category": "",
      "summary": "string",
      "findings": ["string"],
      "recommendations": [
        { "title": "string", "rationale": "string", "action": "string",
          "priority": "low|medium|high", "estimatedImpact": "string?",
          "references": ["string"] }
      ],
      "metrics": { "": "string|number|boolean" },
      "confidence": 0..1,
      "fallbackUsed": boolean,
      "citations": [ /* CitationRef: {key,authors,year,title,venue,finding} */ ]
    }
  ],
  "prioritizedRecommendations": [ /* Recommendation */ ],
  "nextSteps": ["string"],
  "disclaimers": ["string"],
  "citations": [ /* aggregated CitationRef, deduplicated */ ]
}
```
Full schema: `assets/schemas/consultation.schema.json`.

### 5.3 Tool I/O
Every tool exposes `inputSchema` and `outputSchema` (JSON Schema, draft-07 subset).
Inspect at runtime via `skill.tools.listSchemas()`. Validation is enforced by
`validateAgainstSchema` on both input and output of every execution.

## 6. Configuration & feature flags

Type-safe config via Zod (`src/config/schema.ts`). Resolved from defaults + env
overrides (`src/config/env.ts`) or an explicit override document.

| Env var | Default | Effect |
| --- | --- | --- |
| `LOG_LEVEL` | info | log severity |
| `LLM_MODEL` | gpt-4o-mini | primary model |
| `LLM_BASE_URL` | OpenAI | provider endpoint |
| `LLM_TEMPERATURE` / `LLM_MAX_TOKENS` / `LLM_TIMEOUT_MS` / `LLM_MAX_RETRIES` | 0.2 / 2048 / 30000 / 3 | sampling/retry |
| `FC_SOFT_TOKEN_BUDGET` / `FC_HARD_TOKEN_BUDGET` / `FC_RESERVED_OUTPUT_TOKENS` | 6000 / 8000 / 1024 | context policy |
| `FC_ENABLE_COT_ROUTING` | true | chain-of-thought router |
| `FC_ENABLE_PARALLELISM` | false | parallel sub-advisors |
| `FC_ENABLE_TOOL_CACHE` | true | tool result caching |
| `FC_ENABLE_CONTEXT_COMPRESSION` | true | history compression |
| `FC_ENABLE_RAG` | true | reference grounding flag |
| `FC_ENABLE_FALLBACK` | true | graceful degradation |

Config JSON: `config/default.config.json`; schema: `config/config.schema.json`;
flags: `config/feature-flags.json`; example env: `.env.example`.

## 7. Production-grade guarantees

- **No placeholders**: every function is fully implemented (no TODOs/stubs).
- **Type-safe**: strict TypeScript; Zod config + domain validation; JSON-Schema tool I/O.
- **Graceful degradation**: router, advisors, and aggregation all have deterministic
  fallbacks — a schema-valid consultation is **always** returned, even with no LLM.
- **Context management**: `ContextManager` budgets every LLM call to hard token limits
  with configurable compression strategies.
- **Provider failover**: retry + exponential backoff + ordered endpoint failover.
- **Structured logging**: newline-delimited JSON logs via `Logger` (pretty mode in dev).
- **Hooks**: isolated hook execution; failures never abort the consultation.
- **Deterministic numbers**: metrics computed by validated tools and force-merged
  into outputs, so the LLM never invents financial figures.

## 8. Programmatic usage

```ts
import { buildSkill } from "finance-consultant-skill";

const skill = buildSkill();

const consultation = await skill.consult({
  query: "Balance paying off debt, saving for a house, and retirement.",
  profile: { /* FinancialProfile */ },
  focusAreas: ["debt-management", "goal-planning"],
});

console.log(consultation.headlineSummary);
```

CLI scripts:
- `npm run setup` — install, typecheck, build, validate.
- `npm run build` — compile to `dist/`.
- `npm run typecheck` — strict noEmit check.
- `npm run validate` / `npm test` — offline self-validation suite.
- `npm run demo` — end-to-end demo (uses fallback when no API key).
- `npm run seed` — write sample profiles to `assets/seed/`.
- `npm run clean` — remove build artifacts.

## 9. Extension points

- **New tool**: implement `ToolDefinition`, register via `skill.tools.register(tool)`.
- **New advisor**: implement `AdvisorAgent` (id must equal `${category}-advisor`),
  register via `skill.agents.register(advisor)`; the registry self-check covers it.
- **Custom hook**: `skill.hooks.register(stage, id, handler, priority)`.
- **Custom LLM transport**: implement `LlmTransport`, pass via `buildSkill({ llmTransport })`.
- **State persistence**: pass a `stateSink` to `buildSkill` to snapshot session state.

## 11. Research grounding

Recommendations are evidence-backed. `RESEARCH-PAPER-KNOWLEDGE-BRAIN.md` lists **29
curated scientific papers** (life-cycle theory, portfolio theory, retirement
withdrawal, behavioral finance, savings defaults, financial literacy, household
finance, insurance/risk). The machine-readable mirror is
`src/research/citations.ts`.

- Advisor system prompts list the relevant `citation:` keys per specialty.
- Recommendations include `citation:` in their `references` array.
- The orchestrator resolves and dedupes these into a `citations` block on every
  consultation (and per advisor output), each entry carrying authors, year, title,
  venue, and finding.
- The `4% rule`, emergency-fund ordering, allocation-by-risk, and "automate it"
  defaults each trace to specific papers (Bengen 1994; Carroll 1997; Markowitz 1952;
  Madrian & Shea 2001; Chetty et al. 2014).

Integrity: citations are recalled from training; verify against primary sources
before academic/regulatory use.

## 12. RAG grounding layer

When `enableRagGrounding` is on, a dependency-free offline retriever (`src/rag`)
indexes `references/domain/*.md` and injects the top-k snippets relevant to each
advisor's query+category into that advisor's system prompt. The `RagProvider`
interface is pluggable (`LocalMarkdownRagProvider`, `NoopRagProvider`); inject a
custom one via `buildSkill({ rag })`.

## 13. Pluggable tax-jurisdiction providers

Tax estimation is pluggable via `src/tax` (`TaxProviderRegistry`). Built-in:
`us-federal` (default), `flat-10`, `uk-income` (all illustrative). The
`tax-estimator` tool accepts an optional `jurisdiction` and delegates to the
registry. Set the default via config `tax.defaultJurisdiction` (env
`FC_TAX_JURISDICTION`), or register your own provider.

## 14. Session persistence

`src/persistence` provides `MemorySessionStore` (default), `FileSystemSessionStore`
(JSON files, zero deps), and `SqliteSessionStore` (real CRUD via Node 22+
`node:sqlite`, with a clear capability error otherwise). The engine saves state
and resumes by `sessionId`; expose `Skill.loadSession(id)` /
`Skill.listSessions()`. Enable via `buildSkill({ store })` or
`buildSkill({ enablePersistence: true })`.

## 15. Diagnostics & health check

```bash
node scripts/diagnostics.js          # human-readable
node scripts/diagnostics.js --json   # machine-readable
```
Reports skill/agent/tool/hook/research/context/LLM health without network access.
## 16. Disclaimers

Outputs are informational and educational only — not personalized financial, tax, or
legal advice. Projections are estimates based on stated assumptions. Consult a
licensed professional before acting.

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [dungnotnull](https://github.com/dungnotnull)
- **Source:** [dungnotnull/comprehensive-finance-consultant-agent-skill](https://github.com/dungnotnull/comprehensive-finance-consultant-agent-skill)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** yes
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-dungnotnull-comprehensive-finance-consultant-agent-skill-comprehensive-finance-consultant-agent-skill
- Seller: https://agentstack.voostack.com/s/dungnotnull
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
