Skip to content

Issues fixed: LangGraph API agent, AI cost tracking, Windows UTF-8 - #11

Merged
vsn411 merged 6 commits into
mainfrom
fix/issues-fixed
Sep 21, 2026
Merged

vsn411 merged 6 commits into
mainfrom
fix/issues-fixed

Conversation

@geet038

@geet038 geet038 commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

Combines #9 (API-key agent and cost tracking) and #10 (LangGraph agent and cost tracking) into one change, and fixes the bugs found in each. It contains #9's commits plus the fixes, so if this merges, #9 and #10 can both be closed.

Bugs fixed

From #10 (built-in LangGraph agent)

Bug Effect Fix here
The agent never sent the source code to the model. It sent only the rendered prompt, and _target_section() puts just the target's local path in that ("Inspect the codebase at: /tmp/..."). An API model can't open that path. Reports were produced without the model seeing any code, so findings were generic or invented. The unit test asserted messages == [{"role": "user", "content": "review this target"}], so it didn't catch this. collect_files() reads the target (skipping DEFAULT_EXCLUDE_PATHS, binaries and files over 200 KB) and appends each file's path and contents to the message. Targets over 2M characters fail with a clear message.
The LangGraph graph had one node (START -> call_model -> END). LangGraph added a dependency but no behaviour: it was equivalent to one completion() call. The graph now has three nodes and a conditional edge (see below).
langgraph and litellm were added to the core dependencies. Every secfoo user would install both, even users who only use CLI agents. Both are in an optional api extra: pip install "secfoo[api]". If they're missing, the run fails with an install hint.
Unknown cost was stored as NULL but displayed as $0.0000 (the overview's SUM via COALESCE(..., 0)). Runs from agents that don't report cost (Cursor, Antigravity) looked free. Unknown cost renders as "-", and the overview total stays "-" until at least one run has a known cost.
Only cost was tracked, not tokens, and only for the new agent. Spend from claude runs was invisible. Input and output tokens are tracked for every agent that reports them: api (tokens and cost), claude (total_cost_usd and usage), gemini (tokens).
UTF-8 was fixed for report writes only. Reports were then written as UTF-8 but read back in the Windows code page, so text like "—" still came out garbled. Every read_text/write_text in src/ uses UTF-8. Report reads use errors="replace", so reports written by older versions in cp1252 still render. The test suite now gives the same result with or without PYTHONUTF8.
_kill_process_tree (production code) wrapped subprocess.run in except TypeError to suit a test double. Masks real errors in the Windows timeout path. Not carried over.

From #9 (API-key agent)

Bug Effect Fix here
No retry on provider rate limits. Running 7 skills at once against NodeGoat failed prompt-review with OpenAI RateLimitError. completion(..., num_retries=3): LiteLLM backs off and retries on rate limits and transient errors.
A malformed report was saved as-is. Missing **Overall risk rating:** line, so no overall rating on the dashboard. The LangGraph report check requests a reformat once (see below).
An API key pasted with a trailing newline. httpx rejected the auth header, and LiteLLM reported only "Connection error". Keys are trimmed before use.
--agent api was rejected by the CLI. The CLI has its own AgentId enum, separate from ADAPTERS. api added to the enum.
litellm was not declared as a dependency. Fresh installs crashed on import. The api extra plus an install hint.

Kept from #10

Tokens and cost in the secfoo cloud sync payload and in create_completed_run (portal ingestion), secfoo cost --project, the README section and the config.example.toml hint.

How LangGraph is used

LiteLLM is still the only model gateway: it's what talks to OpenAI, Anthropic or Gemini. LangGraph runs the agent's workflow as a state graph and calls LiteLLM inside the assess node.

START -> collect_files -> assess -> [report complete?] --yes--> END
                            ^               |
                            |               no (first attempt only)
                            +-- request_fix <+
Node What it does
collect_files Walks the target and builds one message: the skill prompt followed by each file's path and contents.
assess Calls litellm.completion() with num_retries=3, then adds the call's tokens and cost to the running total in the graph state.
check (conditional edge) Does the report contain **Overall risk rating:**, the line every output contract requires and report/severity.py parses? If yes, or after MAX_ATTEMPTS (2), go to END.
request_fix Builds a new, short conversation: the skill prompt (which includes the output contract) plus the model's own draft, asking it to reformat without adding, dropping or re-rating findings. The source isn't resent, so the retry costs a fraction of the first call.

The graph state carries attempts, input_tokens, output_tokens, cost_usd and unpriced, so usage from both calls is added together. Cost is None if any call couldn't be priced.

Why a graph: today it gives the report check and a clear, inspectable workflow. build_graph(...).get_graph().draw_mermaid() renders the diagram above. It is also the foundation for Tier B, where the model explores large repositories itself with list_files / read_file / grep tools in a loop of unknown length. That becomes a matter of adding tool nodes to this graph rather than rewriting the agent.

How a run works end to end

  1. secfoo run --skill sast --agent api --target <repo>: the runner renders the skill prompt as for any other agent.
  2. ApiAdapter.run() checks for a key (OPENAI_API_KEY, ANTHROPIC_API_KEY or GEMINI_API_KEY), trims it, and invokes the graph with the model from SECFOO_API_MODEL (default openai/gpt-4.1-mini).
  3. The graph returns the report and the summed usage as a standard AgentResult.
  4. The runner saves the report, counts severities and stores input_tokens, output_tokens and cost_usd on the run.
  5. Spend is shown in secfoo run, secfoo list, secfoo cost [--by agent|skill|project] [--since] [--project] and the dashboard (overview card, run page, and assessment and project tables). It is also included in cloud sync.

Existing databases gain the three new columns automatically through _RUNS_MIGRATIONS.

Testing

  • 666 passed. The 6 failures also fail on main on Windows: 4 architecture-diagram tests need secfoo vendor mermaid, one checks POSIX file permissions, and test_timeout_status_does_not_raise fails because the test double lacks the context-manager protocol. CI (Linux, py3.10 and py3.12) passes.
  • New: 11 agent tests run the real LangGraph graph against a faked LiteLLM. They cover file collection and exclusions, the size limit, a missing key, an untrimmed key, missing libraries, the single-call happy path, one reformat without resending the source, the retry cap, API errors and unpriced models. There are also 14 cost tests (storage, migration, cost command incl. --project, run output, dashboard, unknown-as-"-", portal ingestion), 5 usage-parsing tests for claude/gemini, and 1 cloud-payload test.
  • Manual, OWASP NodeGoat with gpt-4.1-mini: the SAST run recorded 61,597 input and 3,261 output tokens, costing $0.0299. That matches the formula (61,597 × $0.40/1M + 3,261 × $1.60/1M) using LiteLLM's price table.

Known limitations

  • Tier A: the whole target must fit in one request. Tier B (tool-using loop) is the follow-up.
  • User --exclude paths are listed in the prompt but not yet skipped by collect_files().
  • Costs come from LiteLLM's bundled price table, and provider discounts such as cached input may make the real bill slightly lower.
  • Only OpenAI has been tested end to end. Anthropic and Gemini use the same LiteLLM path.

🤖 Generated with Claude Code

geet038 and others added 3 commits September 18, 2026 23:39
Add an `api` agent that runs skills by calling OpenAI, Anthropic or
Gemini directly through LiteLLM, so an assessment no longer needs a
coding-agent CLI installed. This is Tier A (context stuffing): the
target's source files, minus the default exclusions, binaries and files
over 200 KB, are sent in one request. Targets over 2M characters are
rejected with a clear message. Install with `pip install "secfoo[api]"`.

Record input/output tokens and cost on every run where the agent
reports them (api via LiteLLM, claude via total_cost_usd, gemini tokens
only), and surface spend in `secfoo run`, `secfoo list`, a new
`secfoo cost` command, and the dashboard. Unknown cost renders as "-",
never $0.00. Existing databases gain the new columns automatically.

Co-Authored-By: Claude Opus 5 <[email protected]>
Rebuild the api agent's run as a LangGraph graph (collect_files ->
assess -> report check), with LiteLLM still the only model gateway. If
a report comes back without the `**Overall risk rating:**` line every
output contract requires, the graph asks the model once to reformat its
own draft -- without resending the source, so the retry stays cheap.
Tokens and cost add up across both calls. LiteLLM now retries rate
limits and transient errors itself (num_retries=3); running several
skills at once previously failed on OpenAI's rate limit.

Fold in the useful parts of PR #10:
- tokens and cost in the cloud-sync payload and create_completed_run
- `secfoo cost --project`, a README section, config.example.toml hint
- UTF-8 for every text read/write, not just runner's report writes.
  Report reads use errors="replace" so reports written by older
  versions in the Windows code page still render instead of crashing.
  The suite now gives the same result with or without PYTHONUTF8.

langgraph joins litellm in the `api` extra, and dev (litellm stays
faked in tests, so CI doesn't need it).

Co-Authored-By: Claude Opus 5 <[email protected]>
vsn411 and others added 3 commits September 21, 2026 17:59
The conflict resolution kept both sides in several places:
- repository.py create_completed_run: two INSERT statements spliced
  together (unclosed paren -> SyntaxError, every test failed) and a
  duplicate cost_usd parameter
- repository.py complete_run: a leftover SQL line from #10 after the
  UPDATE string, so execute() received three arguments
- schema.sql: cost_usd declared twice (duplicate column name)
- cli.py: two `cost` commands and two Cost columns in `list`
- overview/project/run_detail templates: both cost renderings; README:
  interleaved intro sentence and an unclosed code fence

Keep one version of each (the one with tokens and "-" for unknown
cost), drop the now-unused total_cost_usd from the overview route, and
point #10's two `cost` CLI tests at the current command. Both the
`secfoo` and `codex` agents from main are kept.

Co-Authored-By: Claude Opus 5 <[email protected]>
@vsn411
vsn411 merged commit a3052d1 into main Sep 21, 2026
2 of 4 checks passed
AdithKB added a commit to AdithKB/secfoo that referenced this pull request Oct 3, 2026
…odel)

src/secfoo/agents/secfoo.py was the original Initiative-2 draft (PR secfoo-com#10).
PR secfoo-com#11 fixed the exact bug it has -- the agent never reads the target's
files, so the model reviews nothing and fabricates a report -- but fixed
it in a new, separate file (api.py) and never removed this one. Both
have been registered and independently selectable via --agent ever
since, with no indication either is broken.

Reproduced twice against we45/Vulnerable-Flask-App (SAST and Secret
Scanning): --agent secfoo returns "Confirmed" findings at file paths
that don't exist anywhere in the target (app/db.py, app/upload.py,
deploy/ci.yml), because build_graph's _State/run() never wires the
resolved workdir into the model call at all -- collect_files() (the
function that actually reads source) is never called from this file.
The adapter's own test asserts this as correct behavior
(messages == [{"role": "user", "content": "review this target"}]),
so CI can't catch it.

--agent api is the real, fixed implementation and needs no changes.
This just removes the dead duplicate and its now-stale references:
registry, AgentId enum, __init__ exports, its test, and two docs spots
(README's duplicate "built-in LangGraph agent" section, and
config.example.toml's three conflicting `agent =` example lines).

Full suite: 700 passed (down from 702 -- exactly the 2 tests removed
with the dead file). bandit clean on the touched agent files.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants