Skip to content

feat(encoder): add progress logging and incremental cache with token tracking - #55

Merged
amondnet merged 6 commits into
mainfrom
feat/encoder-progress-logging
Feb 11, 2026
Merged

amondnet merged 6 commits into
mainfrom
feat/encoder-progress-logging

Conversation

@amondnet

@amondnet amondnet commented Feb 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR enhances the RPG encoder with comprehensive progress logging, incremental cache saving, and LLM token usage tracking to improve observability and reliability during long-running encoding operations.

Changes

Progress Logging

  • LLM Configuration: Log provider and model on encoder initialization
  • File Progress: Display [n/N] counter with relative file paths during Phase 1
  • Phase Transitions: Log start/completion of each encoding phase (Domain Discovery, Hierarchical Construction, Artifact Grounding)
  • Cache Statistics: Track and report cache hit/miss counts after Phase 1
  • Token Usage: Log cumulative LLM API usage (requests, input tokens, output tokens, total)

Incremental Cache Saving

  • Save cache after each file instead of at the end (survives interruption)
  • Track cache hits/misses for performance insights

CLI & LLM Improvements

  • Update CLI shebang from #!/usr/bin/env bun to #!/usr/bin/env node for broader compatibility
  • Add dotenv dependency for loading .env.local and .env configuration files
  • Add TokenUsageStats interface to LLMClient with getUsageStats() and resetUsageStats() methods
  • Update default LLM models:
    • Anthropic: claude-sonnet-4.5
    • Google: gemini-3-flash-preview
  • Add SemanticExtractor.getLLMClient() accessor for usage statistics

Example Output

[RPGEncoder] LLM: google (gemini-3-flash-preview)
[RPGEncoder] [1/42] src/graph/store.ts
[RPGEncoder] [2/42] src/graph/node.ts
...
[RPGEncoder] Phase 1 done: 15 cache hits, 27 cache misses
[RPGEncoder] Phase 2: Structural Reorganization...
[RPGEncoder] Phase 2.1: Domain Discovery (8 file groups)...
[RPGEncoder] Phase 2.1: Found 5 functional areas: graph, encoder, tools, utils, cli
[RPGEncoder] Phase 2.2: Hierarchical Construction...
[RPGEncoder] Phase 2.2: Done
[RPGEncoder] Phase 3.1: Metadata propagation...
[RPGEncoder] Phase 3.2: Dependency injection...
[RPGEncoder] Phase 3.3: Data flow detection...
[RPGEncoder] LLM usage: 42 requests, 125,430 input + 8,234 output = 133,664 total tokens

Benefits

  1. Observability: Users can track encoding progress and understand what phase is running
  2. Cost Visibility: Token usage tracking helps estimate LLM API costs
  3. Reliability: Incremental cache saving prevents data loss on interruption
  4. Performance Insights: Cache hit/miss statistics reveal semantic extraction efficiency
  5. Configuration Flexibility: .env.local support for local API key management

Test Plan

  • Run encoder on sample repository and verify progress logs appear
  • Verify cache statistics are accurate
  • Verify token usage matches actual LLM API calls
  • Test interruption scenario (cache survives Ctrl+C)
  • Verify dotenv loads .env.local correctly

Related Issues

This improves the developer experience for the encoder functionality introduced in previous PRs.


Summary by cubic

Adds detailed progress logging, incremental cache saves, token usage/cost tracking, and stronger error handling/timeouts to make long encoding runs easier to monitor and more resilient. Also updates the CLI to use Node, load env files, refreshes default LLM models, and cleans up MCP config.

  • New Features

    • Logs provider/model, per-file progress [n/N], and phase transitions.
    • Saves cache after each file; reports cache hits/misses.
    • Tracks cumulative usage across modules and prints estimated cost (~$X.XXXX).
    • Adds 120s timeout and onError; wraps extraction and reorg steps; continues on failures with warnings.
    • CLI uses node and loads .env.local/.env; default models updated; extractor exposes LLM client.
  • Refactors

    • Ignore entire .please/memory/ in .gitignore.
    • Streamlined token stats with INITIAL_USAGE_STATS and array-based aggregation; interface placement cleanup.
    • Fix strict index access in encoder loop; reorder CLI imports; remove SonarQube server from .mcp.json.

Written for commit c4773bf. Summary will update on new commits.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @amondnet, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly upgrades the RPG encoder's operational transparency and resilience. It introduces robust logging for real-time progress monitoring, implements an incremental caching mechanism to safeguard against data loss, and integrates comprehensive LLM token usage tracking for cost and performance analysis. These enhancements aim to provide users with a more reliable, observable, and cost-aware encoding experience.

Highlights

  • Enhanced Progress Logging: The encoder now provides detailed progress logs, including LLM configuration, file processing status (e.g., [n/N] files), and clear phase transitions (Domain Discovery, Hierarchical Construction, Artifact Grounding). This significantly improves observability during long-running encoding operations.
  • Incremental Cache Saving: The semantic cache is now saved after processing each file, rather than only at the end. This change enhances reliability by ensuring that progress is preserved even if the encoding process is interrupted.
  • LLM Token Usage Tracking: Cumulative LLM API usage statistics (requests, input tokens, output tokens, total tokens) are now tracked and reported at the end of the encoding process, providing better cost visibility and performance insights.
  • Cache Performance Insights: The encoder tracks and reports cache hit and miss counts after Phase 1, offering valuable data on the efficiency of semantic extraction and cache utilization.
  • CLI and LLM Improvements: The CLI shebang was updated for broader compatibility, dotenv support was added for flexible configuration management, and default LLM models for Anthropic and Google were updated to newer versions. An accessor for the LLM client was also added to the SemanticExtractor for usage statistics.
Changelog
  • bun.lock
    • Added dotenv dependency.
  • package.json
    • Added dotenv dependency.
  • src/cli.ts
    • Updated shebang from bun to node for broader compatibility.
    • Imported and configured dotenv to load .env.local and .env configuration files.
  • src/encoder/encoder.ts
    • Initialized cacheHits and cacheMisses counters.
    • Logged LLM provider and model upon encoder initialization.
    • Implemented file-by-file progress logging during Phase 1.
    • Changed cache saving mechanism to occur incrementally after each file is processed.
    • Logged cache hit and miss statistics after Phase 1 completion.
    • Added console logging for the start of Phase 2 and its sub-phases (Domain Discovery, Hierarchical Construction).
    • Added console logging for the start of Phase 3 sub-phases (Metadata propagation, Dependency injection, Data flow detection).
    • Incremented cacheHits or cacheMisses based on semantic cache lookup results.
    • Logged cumulative LLM token usage statistics at the end of the encoding process.
  • src/encoder/semantic.ts
    • Added getLLMClient() method to provide access to the internal LLM client for usage statistics.
  • src/utils/llm.ts
    • Updated default Anthropic model to claude-sonnet-4.5.
    • Updated default Google model to gemini-3-flash-preview.
    • Defined TokenUsageStats interface for tracking LLM usage metrics.
    • Added usageStats property to LLMClient to store cumulative token usage.
    • Modified the post method to accumulate token usage and request counts.
    • Added getUsageStats() method to retrieve the current cumulative token usage statistics.
    • Added resetUsageStats() method to clear the accumulated token usage statistics.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@codecov

codecov Bot commented Feb 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 41.53846% with 76 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/utils/llm.ts 32.20% 40 Missing ⚠️
src/encoder/encoder.ts 47.05% 36 Missing ⚠️

📢 Thoughts on this report? Let us know!

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces excellent enhancements for observability and reliability in the RPG encoder. The progress logging, incremental cache saving, and LLM token usage tracking are valuable additions. The code is well-structured and the changes are clearly implemented. I've added a couple of minor suggestions to improve maintainability by reducing code duplication and making the statistics aggregation more scalable. Overall, this is a great contribution.

Comment thread src/encoder/encoder.ts Resolved
Comment thread src/utils/llm.ts Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 6 files

Prompt for AI agents (all issues)

Check if these issues are valid — if so, understand the root cause of each and fix them.


<file name="src/utils/llm.ts">

<violation number="1" location="src/utils/llm.ts:97">
P2: The `TokenUsageStats` interface is inserted between the `LLMClient` class JSDoc and the class declaration, breaking the JSDoc association. Move the interface definition *above* the class JSDoc block (e.g., after `createProvider`) so the class documentation remains properly attached.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Comment thread src/utils/llm.ts Resolved
…tracking

Added comprehensive progress logging to track encoding phases and LLM usage:
- Log LLM configuration on encoder initialization
- Display file progress with [n/N] counter and relative paths
- Show phase transitions (Domain Discovery, Hierarchical Construction, etc.)
- Track and report cache hit/miss statistics
- Log cumulative LLM token usage (requests, input/output tokens)

Improved cache reliability:
- Save cache incrementally after each file (survives interruption)
- Track cache hits/misses for statistics

Enhanced CLI and LLM client:
- Updated CLI shebang to #!/usr/bin/env node for broader compatibility
- Added dotenv support for loading .env.local and .env files
- Added TokenUsageStats tracking to LLMClient (getUsageStats, resetUsageStats)
- Updated default models: claude-sonnet-4.5, gemini-3-flash-preview
- Added SemanticExtractor.getLLMClient() accessor for usage stats

This improves observability during long-running encoding operations and
provides insights into LLM API costs and cache effectiveness.
…estimation

- Add MODEL_PRICING table for cost estimation across providers (OpenAI, Anthropic, Google)
- Implement estimateCost() method in LLMClient to calculate input/output costs
- Add 120s timeout with AbortSignal to prevent hanging requests
- Add onError callback for custom error handling
- Wrap file extraction in try/catch with detailed error logging
- Wrap Phase 2 steps (domain discovery, hierarchy builder) in try/catch
- Display estimated cost in LLM usage summary (~$X.XXXX format)
- Log extraction failures as warnings and continue processing remaining files

This enhances the encoder progress logging PR with better observability
and resilience for production use.
Replace .please/memory/session-summary.md with .please/memory/
to ignore all memory files generated by Please AI.
- Refactor token stats aggregation to use array methods (gemini-code-assist)
- Extract INITIAL_USAGE_STATS constant to avoid duplication (gemini-code-assist)
- Move TokenUsageStats interface above LLMClient class JSDoc (cubic-dev-ai)
@amondnet
amondnet force-pushed the feat/encoder-progress-logging branch from 70b00aa to c4773bf Compare February 11, 2026 18:20
@amondnet
amondnet enabled auto-merge (squash) February 11, 2026 18:20
@amondnet
amondnet merged commit 4ddd490 into main Feb 11, 2026
5 of 6 checks passed
@amondnet
amondnet deleted the feat/encoder-progress-logging branch February 11, 2026 18:23
@sonarqubecloud

Copy link
Copy Markdown

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.

1 participant