Skip to content

fix(synapse): dynamic context window from model registry instead of hardcoded 200K#606

Open
LeandroMachadoAveiro wants to merge 2 commits intoSynkraAI:mainfrom
LeandroMachadoAveiro:fix/synapse-dynamic-context-window
Open

fix(synapse): dynamic context window from model registry instead of hardcoded 200K#606
LeandroMachadoAveiro wants to merge 2 commits intoSynkraAI:mainfrom
LeandroMachadoAveiro:fix/synapse-dynamic-context-window

Conversation

@LeandroMachadoAveiro
Copy link

@LeandroMachadoAveiro LeandroMachadoAveiro commented Mar 15, 2026

Summary

  • context-tracker.js hardcoded maxContext: 200000 causes premature bracket escalation on Opus 4.6 (1M context) — CRITICAL fires at ~66 prompts when 80%+ context remains
  • Added models section to core-config.yaml with model registry (context window + avg tokens per model)
  • getModelConfig() reads active model dynamically, cached per process, graceful fallback to 200K

Impact

Prompts Before (200K) After (1M — Opus 4.6)
50 32.5% → DEPLETED 91% → FRESH
100 10% → CRITICAL 82% → FRESH
133 0% → CRITICAL 76% → FRESH

Files Changed

  • .aios-core/core-config.yaml — added models section with registry
  • .aios-core/core/synapse/context/context-tracker.js — v1.0.0 → v1.1.0, dynamic config reader

Migration Guide

Add to your project core-config.yaml:

models:
  active: claude-opus-4-6  # or claude-sonnet-4-6, claude-haiku-4-5
  registry:
    claude-opus-4-6:
      contextWindow: 1000000
      avgTokensPerPrompt: 1500
    claude-sonnet-4-6:
      contextWindow: 200000
      avgTokensPerPrompt: 1500
    claude-haiku-4-5:
      contextWindow: 200000
      avgTokensPerPrompt: 1200

Without this section, the tracker falls back to the previous 200K default (backward-compatible).

Test plan

  • Verify estimateContextPercent(100) returns ~82% with Opus config (1M)
  • Verify fallback to 200K when models section is missing
  • Verify resetModelConfigCache() clears cache for test isolation
  • Verify .aios-core and .aiox-core paths both resolve

Closes #605

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Chores
    • Updated model configuration to support multiple AI models with context window and token settings. Introduces an active model selection mechanism and a model registry enabling flexible model management.

@vercel
Copy link

vercel bot commented Mar 15, 2026

@LeandroMachadoAveiro is attempting to deploy a commit to the Pedro Valério Lopez's projects Team on Vercel.

A member of the Team first needs to authorize it.

@github-actions github-actions bot added area: agents Agent system related area: workflows Workflow system related squad mcp type: test Test coverage and quality area: core Core framework (.aios-core/core/) area: installer Installer and setup (packages/installer/) area: synapse SYNAPSE context engine area: cli CLI tools (bin/, packages/aios-pro-cli/) area: pro Pro features (pro/) area: health-check Health check system area: docs Documentation (docs/) area: devops CI/CD, GitHub Actions (.github/) labels Mar 15, 2026
@coderabbitai
Copy link

coderabbitai bot commented Mar 15, 2026

Walkthrough

Adds a new model registry configuration block under the boundary section in the core configuration, specifying context window sizes and average token consumption for three Claude model variants with Opus designated as the active model.

Changes

Cohort / File(s) Summary
Model Registry Configuration
.aiox-core/core-config.yaml
Added models section with active model designation and registry containing contextWindow and avgTokensPerPrompt settings for Claude Opus (1M context), Sonnet (200K), and Haiku (200K) variants.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~2 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: replacing hardcoded 200K context with dynamic model registry configuration.
Linked Issues check ✅ Passed The pull request implementation addresses all core objectives from #605: model registry in core-config.yaml, dynamic context window reading via getModelConfig(), per-process caching with fallback to 200K default, resetModelConfigCache() export for tests, and version bump.
Out of Scope Changes check ✅ Passed All changes are directly scoped to #605 requirements: configuration addition and context-tracker implementation. No extraneous modifications or unrelated refactoring detected.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Tip

You can make CodeRabbit's review stricter and more nitpicky using the `assertive` profile, if that's what you prefer.

Change the reviews.profile setting to assertive to make CodeRabbit's nitpick more issues in your PRs.

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Welcome to aiox-core! Thanks for your first pull request.

What happens next?

  1. Automated checks will run on your PR
  2. A maintainer will review your changes
  3. Once approved, we'll merge your contribution!

PR Checklist:

Thanks for contributing!

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
.aios-core/core/synapse/context/context-tracker.js (1)

108-111: Silent error swallowing may obscure configuration issues.

The catch block falls back to defaults without any logging or indication that an error occurred. This could make it difficult to diagnose issues such as YAML syntax errors, permission problems, or unexpected config structures.

🔧 Proposed improvement

Consider logging a warning when falling back due to an error (not just missing config):

   } catch (_err) {
+    if (process.env.DEBUG || process.env.NODE_ENV !== 'production') {
+      console.warn('[context-tracker] Failed to load model config, using defaults:', _err.message);
+    }
     _modelConfigCache = DEFAULTS;
     return _modelConfigCache;
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.aios-core/core/synapse/context/context-tracker.js around lines 108 - 111,
The catch block that assigns _modelConfigCache = DEFAULTS is silently swallowing
errors; modify the catch in the function that loads/parses the model config so
it logs a warning (including the caught error object/message and context like
the config path or source) before falling back to DEFAULTS; specifically update
the catch that currently uses ( _err ) and references _modelConfigCache and
DEFAULTS to call the existing logger (or console.warn if none) with a clear
message and the error details to aid debugging.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.aios-core/core/synapse/context/context-tracker.js:
- Around line 79-82: The code uses process.cwd() to construct configPath which
can break when the working directory is changed; update context-tracker.js to
resolve the config file relative to the module or an explicit base path instead:
replace process.cwd() usage in the configPath construction with a
module-relative resolution (e.g., using __dirname or an injected basePath
parameter) and implement a small upward directory walk from that base to locate
'.aios-core/core-config.yaml' (with the same fallback to
'.aiox-core/core-config.yaml') so the lookup is robust to chdir or test changes;
key symbols to modify are the configPath assignment and any initializer that
imports this module so it can optionally accept a basePath.

---

Nitpick comments:
In @.aios-core/core/synapse/context/context-tracker.js:
- Around line 108-111: The catch block that assigns _modelConfigCache = DEFAULTS
is silently swallowing errors; modify the catch in the function that
loads/parses the model config so it logs a warning (including the caught error
object/message and context like the config path or source) before falling back
to DEFAULTS; specifically update the catch that currently uses ( _err ) and
references _modelConfigCache and DEFAULTS to call the existing logger (or
console.warn if none) with a clear message and the error details to aid
debugging.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: fac3c96c-4242-4de6-a7d0-8683944fe054

📥 Commits

Reviewing files that changed from the base of the PR and between f74e3e7 and cddbd00.

📒 Files selected for processing (2)
  • .aios-core/core-config.yaml
  • .aios-core/core/synapse/context/context-tracker.js

Comment on lines +79 to +82
let configPath = path.join(process.cwd(), '.aios-core', 'core-config.yaml');
if (!fs.existsSync(configPath)) {
configPath = path.join(process.cwd(), '.aiox-core', 'core-config.yaml');
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Consider using module-relative path resolution instead of process.cwd().

The context snippets show that bin/aios.js uses process.chdir(targetPath) before running commands, and tests may change cwd to temporary directories. Using process.cwd() here could cause the config lookup to fail unexpectedly when:

  1. The CLI is invoked from a subdirectory
  2. Tests change the working directory before importing this module
  3. The module is cached before a chdir occurs

The fallback to DEFAULTS prevents crashes, but users may not realize they're not using their intended model configuration.

💡 Suggested approach

Consider accepting an optional base path parameter or using __dirname to resolve relative to the module's location, then walking up to find the project root:

-function getModelConfig() {
+function getModelConfig(basePath = null) {
   if (_modelConfigCache) return _modelConfigCache;

   try {
     const yaml = require('js-yaml');
-    let configPath = path.join(process.cwd(), '.aios-core', 'core-config.yaml');
+    const root = basePath || process.cwd();
+    let configPath = path.join(root, '.aios-core', 'core-config.yaml');
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.aios-core/core/synapse/context/context-tracker.js around lines 79 - 82, The
code uses process.cwd() to construct configPath which can break when the working
directory is changed; update context-tracker.js to resolve the config file
relative to the module or an explicit base path instead: replace process.cwd()
usage in the configPath construction with a module-relative resolution (e.g.,
using __dirname or an injected basePath parameter) and implement a small upward
directory walk from that base to locate '.aios-core/core-config.yaml' (with the
same fallback to '.aiox-core/core-config.yaml') so the lookup is robust to chdir
or test changes; key symbols to modify are the configPath assignment and any
initializer that imports this module so it can optionally accept a basePath.

LeandroMachadoAveiro and others added 2 commits March 15, 2026 16:22
…ardcoded 200K

The context-tracker was hardcoded to 200K tokens, causing premature bracket
escalation on Opus 4.6 (1M context). Now reads active model from
core-config.yaml models.registry with graceful fallback to 200K default.

Closes SynkraAI#605

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Address CodeRabbit review findings:
- Replace process.cwd() with __dirname-based resolution for config path lookup
- Add optional basePath parameter to getModelConfig() for test injection
- Log warning when config loading fails (only in DEBUG/AIOX_DEBUG mode)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@LeandroMachadoAveiro LeandroMachadoAveiro force-pushed the fix/synapse-dynamic-context-window branch from cddbd00 to 192b3c3 Compare March 15, 2026 19:28
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
.aiox-core/core-config.yaml (1)

388-391: Minor: Comment references MIS-2+ but this serves context-tracker.

Line 388 mentions "Memory Intelligence System (Epic MIS) configuration placeholder — MIS-2+" as a section header, but the models section is being introduced for context-tracker.js to read dynamic context windows (per PR #606 / Issue #605). Consider updating the comment to reflect the actual purpose, or adding a separate comment for clarity.

📝 Suggested comment update
 # Memory Intelligence System (Epic MIS) configuration placeholder — MIS-2+
+# Model registry for dynamic context window configuration (Issue `#605`)
 models:
   active: claude-sonnet-4-6
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.aiox-core/core-config.yaml around lines 388 - 391, Update the YAML section
comment to accurately describe that this `models` block is used by
context-tracker.js to provide dynamic context window configuration (per PR `#606`
/ Issue `#605`) rather than the generic "Memory Intelligence System (Epic MIS) —
MIS-2+" label; edit the header above `models:` (the lines mentioning "Memory
Intelligence System..." and/or "MIS-2+") so it clearly states purpose and scope
(e.g., "Context-tracker dynamic model/config registry for context windowing")
and optionally mention `active: claude-sonnet-4-6` and `registry:` as the fields
consumed by context-tracker.js.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In @.aiox-core/core-config.yaml:
- Around line 388-391: Update the YAML section comment to accurately describe
that this `models` block is used by context-tracker.js to provide dynamic
context window configuration (per PR `#606` / Issue `#605`) rather than the generic
"Memory Intelligence System (Epic MIS) — MIS-2+" label; edit the header above
`models:` (the lines mentioning "Memory Intelligence System..." and/or "MIS-2+")
so it clearly states purpose and scope (e.g., "Context-tracker dynamic
model/config registry for context windowing") and optionally mention `active:
claude-sonnet-4-6` and `registry:` as the fields consumed by context-tracker.js.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2828c818-1c64-4683-a242-d9ae61f2049d

📥 Commits

Reviewing files that changed from the base of the PR and between cddbd00 and 192b3c3.

📒 Files selected for processing (1)
  • .aiox-core/core-config.yaml

@nikolasdehor
Copy link
Contributor

Excelente fix. O hardcode de 200K no context-tracker era uma bomba-relógio — qualquer modelo com janela diferente ia ter estimativas completamente erradas. Observações:

  1. Abordagem de cache: O _modelConfigCache com leitura única por processo é eficiente. Porém, se o usuário trocar o models.active no YAML durante uma sessão longa, o tracker vai continuar com o valor antigo. O resetModelConfigCache() resolve pra testes, mas talvez valha expor uma forma de invalidar em runtime (ou fazer TTL-based cache).

  2. Dual directory: Boa a checagem .aios-core.aiox-core pra compatibilidade com ambas as convenções do projeto.

  3. Dependência do js-yaml: O require('js-yaml') dentro da função (lazy load) é inteligente, mas se o pacote não estiver instalado, o catch silencia o erro e cai no fallback. Talvez logar um warning mesmo sem DEBUG — o dev pode não perceber que o config não está sendo lido.

  4. Tabela de impacto no PR description: Muito boa a comparação antes/depois. Facilita demais o review.

  5. Sugestão menor: No core-config.yaml, considerar adicionar um campo description ou comentário YAML em cada modelo do registry, pra documentar de onde veio o valor de contextWindow (ex: # source: anthropic docs 2026-03).

Aprovado da minha parte — o fallback gracioso garante retrocompatibilidade.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: agents Agent system related area: cli CLI tools (bin/, packages/aios-pro-cli/) area: core Core framework (.aios-core/core/) area: devops CI/CD, GitHub Actions (.github/) area: docs Documentation (docs/) area: health-check Health check system area: installer Installer and setup (packages/installer/) area: pro Pro features (pro/) area: synapse SYNAPSE context engine area: workflows Workflow system related mcp squad type: test Test coverage and quality

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(synapse): context-tracker hardcoded to 200K — should read model context window dynamically

2 participants