Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: pin a 128K numCtx on the Ollama-backed Claude harnesses (#6191)

[._.]/ Adam Eivy0f23d938c9f4
diff --git a/data.reference/providers.json b/data.reference/providers.json
index dbfa649d8a..6cd444d6c8 100644
--- a/data.reference/providers.json
+++ b/data.reference/providers.json
@@ -44,6 +44,7 @@
"models": [],
"defaultModel": null,
"ollamaBacked": true,
+ "numCtx": 131072,
"temperature": 0.6,
"thinking": true,
"timeout": 600000,
@@ -146,6 +147,7 @@
"models": [],
"defaultModel": null,
"ollamaBacked": true,
+ "numCtx": 131072,
"temperature": 0.6,
"thinking": true,
"timeout": 600000,
diff --git a/scripts/migrations/339-claude-ollama-num-ctx.js b/scripts/migrations/339-claude-ollama-num-ctx.js
new file mode 100644
index 0000000000..fa331931ea
--- /dev/null
+++ b/scripts/migrations/339-claude-ollama-num-ctx.js
@@ -0,0 +1,92 @@
+/**
+ * Pin a 128K context window on the Ollama-backed Claude harness records (#6191).
+ *
+ * `claude-ollama` / `claude-ollama-tui` shipped with no `numCtx`, so
+ * `ensureOllamaAgentContext` (server/services/ollamaAgentContext.js) never
+ * reloaded the daemon and Ollama's VRAM-based auto-pick stood. On a large-VRAM
+ * machine that resolves to a 262144-token window, and prefill throughput decays
+ * as the KV cache grows: a ~98K-token pr-reviewer Stage 3 prompt was measured
+ * at 88 tok/s early and 48 tok/s by the end — roughly half an hour of prefill
+ * before the first token. Halving the window halves the KV bandwidth that
+ * causes the decay while still clearing the ~100K-token Stage 3 envelope with
+ * headroom. 32768 (what the `ollama` api-type provider defaults to) is SMALLER
+ * than that envelope and would turn a slow run into a refused one.
+ *
+ * What this migration deliberately does NOT do:
+ *
+ * - **It never overwrites a window the user picked.** Only a record with no
+ * usable `numCtx` is stamped.
+ * - **It never touches a record repointed at another binary.** Keyed on the
+ * `ollamaBacked` marker plus the `claude` command, matching
+ * `isOllamaBackedProvider` + the harness these defaults describe, so a
+ * renamed clone of the shipped record is covered and a record now running
+ * someone's wrapper is not.
+ *
+ * `numCtx: null` counts as UNSET, not as "the user asked for Ollama's
+ * auto-pick": `createProvider` in server/lib/aiToolkit/providers.js normalizes
+ * every absent value to `null` on write, so a stored `null` is indistinguishable
+ * from never having been set and is the state essentially every real install is
+ * in. Treating it as user intent would make this migration a no-op exactly
+ * where it is needed.
+ *
+ * Kept in lockstep with data.reference/providers.json. Later default changes
+ * require a new migration.
+ */
+
+import { readProvidersDoc, writeJsonAtomic } from './_lib.js';
+
+const NUM_CTX = 131072;
+const CLAUDE_COMMAND = 'claude';
+
+// Logged relative, never as `doc.path` — that is an absolute path carrying the
+// operator's home directory, and a boot line is the wrong place to print it.
+const PROVIDERS_REL_PATH = 'data/providers.json';
+
+// `readProvidersDoc` is deliberately silent so each caller can say what ITS skip
+// costs the user; this is 339's copy of that message.
+const SKIP_REASONS = {
+ 'no-file': 'not present (a fresh install seeds these from data.reference)',
+ unreadable: 'is not valid JSON',
+ 'bad-shape': 'has no providers map',
+};
+
+/** A positive integer window, or null when the field carries no usable value. */
+const usableNumCtx = (value) => {
+ const n = Number(value);
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : null;
+};
+
+/**
+ * Is this record still an Ollama-backed Claude harness with no window pinned?
+ *
+ * Command matching is byte-for-byte the rule `lib/providerModels.commandBasename`
+ * applies (inlined because a migration is a frozen snapshot and must not drift
+ * when that helper changes): case-INSENSITIVE basename, only `.exe` stripped.
+ */
+const needsNumCtx = (provider) => {
+ if (provider?.type !== 'cli' && provider?.type !== 'tui') return false;
+ if (provider.ollamaBacked !== true) return false;
+ if (usableNumCtx(provider.numCtx)) return false;
+ const command = typeof provider.command === 'string' ? provider.command.trim() : '';
+ if (command === '') return false;
+ return command.split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '') === CLAUDE_COMMAND;
+};
+
+export default {
+ async up({ rootDir }) {
+ const doc = await readProvidersDoc({ rootDir });
+ if (!doc.ok) {
+ const why = SKIP_REASONS[doc.reason] ?? 'could not be read';
+ console.log(`📄 ${PROVIDERS_REL_PATH} ${why} — skipping the Claude Ollama context-window pin`);
+ return { ok: false, reason: doc.reason, updated: 0 };
+ }
+
+ const targets = Object.values(doc.providers).filter(needsNumCtx);
+ if (targets.length === 0) return { ok: true, reason: 'already-current-or-custom', updated: 0 };
+
+ for (const provider of targets) provider.numCtx = NUM_CTX;
+ await writeJsonAtomic(doc.path, doc.config);
+ console.log(`📝 ${PROVIDERS_REL_PATH}: ${targets.length} Claude Ollama provider record${targets.length === 1 ? '' : 's'} pinned to a ${NUM_CTX}-token context window`);
+ return { ok: true, reason: 'updated', updated: targets.length };
+ },
+};
diff --git a/scripts/migrations/339-claude-ollama-num-ctx.test.js b/scripts/migrations/339-claude-ollama-num-ctx.test.js
new file mode 100644
index 0000000000..77ab06ec10
--- /dev/null
+++ b/scripts/migrations/339-claude-ollama-num-ctx.test.js
@@ -0,0 +1,119 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration from './339-claude-ollama-num-ctx.js';
+
+const CLAUDE_OLLAMA = {
+ id: 'claude-ollama',
+ name: 'Claude Ollama (local model)',
+ type: 'cli',
+ command: 'claude',
+ ollamaBacked: true,
+ enabled: false,
+};
+
+describe('migration 339 — claude-ollama context window pin', () => {
+ let rootDir;
+ let providersPath;
+
+ const writeProviders = (providers) => {
+ mkdirSync(join(rootDir, 'data'), { recursive: true });
+ writeFileSync(providersPath, `${JSON.stringify({ activeProvider: 'claude', providers }, null, 2)}\n`);
+ };
+ const readProviders = () => JSON.parse(readFileSync(providersPath, 'utf8')).providers;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-339-'));
+ providersPath = join(rootDir, 'data', 'providers.json');
+ });
+
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+ it('skips a fresh install with no providers.json (data.reference already ships the window)', async () => {
+ await expect(migration.up({ rootDir })).resolves.toEqual({ ok: false, reason: 'no-file', updated: 0 });
+ });
+
+ it('pins 131072 on a record that carries no numCtx', async () => {
+ writeProviders({ 'claude-ollama': { ...CLAUDE_OLLAMA } });
+
+ await expect(migration.up({ rootDir })).resolves.toEqual({ ok: true, reason: 'updated', updated: 1 });
+
+ const provider = readProviders()['claude-ollama'];
+ expect(provider.numCtx).toBe(131072);
+ expect(provider).toMatchObject(CLAUDE_OLLAMA);
+ });
+
+ it('treats a normalized null numCtx as unset', async () => {
+ // `createProvider` writes `numCtx: null` for every absent value, so a stored
+ // null is indistinguishable from never-set — and is the state essentially
+ // every real install is in. Skipping it would make this migration a no-op.
+ writeProviders({ 'claude-ollama': { ...CLAUDE_OLLAMA, numCtx: null } });
+
+ await expect(migration.up({ rootDir })).resolves.toEqual({ ok: true, reason: 'updated', updated: 1 });
+ expect(readProviders()['claude-ollama'].numCtx).toBe(131072);
+ });
+
+ it('stamps every Ollama-backed Claude harness record, clones included, and leaves others alone', async () => {
+ writeProviders({
+ 'claude-ollama': { ...CLAUDE_OLLAMA, command: '/opt/bin/claude', name: 'My Claude Ollama' },
+ 'claude-ollama-tui': { ...CLAUDE_OLLAMA, id: 'claude-ollama-tui', type: 'tui' },
+ 'claude-ollama-review': { ...CLAUDE_OLLAMA, id: 'claude-ollama-review', command: 'CLAUDE.EXE' },
+ // Ollama-backed but a different harness: OpenCode sizes its own window.
+ 'opencode-ollama': { id: 'opencode-ollama', type: 'cli', command: 'opencode', ollamaBacked: true },
+ // The cloud Claude CLI is not Ollama-backed at all.
+ claude: { id: 'claude', type: 'cli', command: 'claude', enabled: true },
+ ollama: { id: 'ollama', type: 'api', endpoint: 'http://localhost:11434/v1' },
+ });
+
+ await expect(migration.up({ rootDir })).resolves.toEqual({ ok: true, reason: 'updated', updated: 3 });
+
+ const providers = readProviders();
+ for (const id of ['claude-ollama', 'claude-ollama-tui', 'claude-ollama-review']) {
+ expect(providers[id].numCtx).toBe(131072);
+ }
+ expect(providers['opencode-ollama'].numCtx).toBeUndefined();
+ expect(providers.claude.numCtx).toBeUndefined();
+ expect(providers.ollama).toEqual({ id: 'ollama', type: 'api', endpoint: 'http://localhost:11434/v1' });
+ });
+
+ it('leaves a window the user chose alone, larger or smaller', async () => {
+ writeProviders({
+ 'claude-ollama': { ...CLAUDE_OLLAMA, numCtx: 32768 },
+ 'claude-ollama-tui': { ...CLAUDE_OLLAMA, id: 'claude-ollama-tui', type: 'tui', numCtx: 262144 },
+ });
+
+ await expect(migration.up({ rootDir })).resolves.toEqual({
+ ok: true, reason: 'already-current-or-custom', updated: 0,
+ });
+
+ const providers = readProviders();
+ expect(providers['claude-ollama'].numCtx).toBe(32768);
+ expect(providers['claude-ollama-tui'].numCtx).toBe(262144);
+ });
+
+ it('leaves a record the user repointed at a different binary untouched', async () => {
+ writeProviders({ 'claude-ollama': { ...CLAUDE_OLLAMA, command: 'my-wrapper' } });
+
+ await expect(migration.up({ rootDir })).resolves.toEqual({
+ ok: true, reason: 'already-current-or-custom', updated: 0,
+ });
+ expect(readProviders()['claude-ollama'].numCtx).toBeUndefined();
+ });
+
+ it('is a no-op on a second run', async () => {
+ writeProviders({ 'claude-ollama': { ...CLAUDE_OLLAMA } });
+ await migration.up({ rootDir });
+
+ await expect(migration.up({ rootDir })).resolves.toEqual({
+ ok: true, reason: 'already-current-or-custom', updated: 0,
+ });
+ });
+
+ it('reports an unreadable providers.json instead of throwing', async () => {
+ mkdirSync(join(rootDir, 'data'), { recursive: true });
+ writeFileSync(providersPath, '{ not json');
+
+ await expect(migration.up({ rootDir })).resolves.toEqual({ ok: false, reason: 'unreadable', updated: 0 });
+ });
+});
diff --git a/server/lib/ollamaContext.test.js b/server/lib/ollamaContext.test.js
index 3bca2d8a17..31414d46b8 100644
--- a/server/lib/ollamaContext.test.js
+++ b/server/lib/ollamaContext.test.js
@@ -9,6 +9,24 @@ import {
resolveOllamaContextLength,
withOllamaContextEnv
} from './ollamaContext.js'
+import { readFileSync } from 'node:fs'
+
+// Read, not `import … with { type: 'json' }` — the repo avoids JSON import
+// attributes (see promptSystemStages.js).
+const SHIPPED_PROVIDERS = JSON.parse(readFileSync(new URL('../../data.reference/providers.json', import.meta.url), 'utf8'))
+
+// The Ollama-backed Claude harnesses speak to the daemon directly, so the ONLY
+// window they ever get is the one `ensureOllamaAgentContext` reloads the daemon
+// at — i.e. whatever `resolveOllamaContextLength` returns for their seeded
+// record. Shipping them without a `numCtx` left Ollama's VRAM auto-pick in
+// charge, which on a large-VRAM machine is a 262K window whose prefill decays
+// as the KV cache grows (#6191).
+const CLAUDE_OLLAMA_HARNESS_IDS = ['claude-ollama', 'claude-ollama-tui']
+
+// A pr-reviewer Stage 3 prompt was measured at ~98K tokens, so the seeded window
+// must clear that envelope with headroom — a window BELOW it turns a slow run
+// into a refused one (`exceed_context_size_error`).
+const STAGE_3_PROMPT_ENVELOPE = 100_000
describe('resolveOllamaContextLength', () => {
it('prefers the provider numCtx over the ambient env', () => {
@@ -133,3 +151,17 @@ describe('isSameOllamaDaemon', () => {
expect(isSameOllamaDaemon('http://', 'http://localhost:11434')).toBe(false)
})
})
+
+describe('shipped Claude Ollama harness seeds', () => {
+ for (const id of CLAUDE_OLLAMA_HARNESS_IDS) {
+ it(`${id} resolves to a window above the Stage 3 envelope with no ambient env`, () => {
+ const provider = SHIPPED_PROVIDERS.providers[id]
+ expect(provider, `data.reference/providers.json is missing ${id}`).toBeDefined()
+ // Empty env on purpose: the seed alone must be enough, because an install
+ // that never set OLLAMA_CONTEXT_LENGTH is the default case.
+ const resolved = resolveOllamaContextLength(provider, {})
+ expect(resolved, `${id} must pin a numCtx — without one Ollama's VRAM auto-pick stands`).not.toBeNull()
+ expect(resolved).toBeGreaterThan(STAGE_3_PROMPT_ENVELOPE)
+ })
+ }
+})