Cohezion accumulates rich execution experience (phi_score, 12D FLUME trajectories, coherence
metrics) via JourneyTracker but never uses it to update model weights. Four training pipelines
exist in flume/ but all generate bash scripts and stop — none execute training. Meanwhile
cloud API costs accumulate on Claude Code / Gemini CLI every session.
The goal is a closed Cohezion Autonomous Learning Loop (CALL): Cohezion's own runtime
experiences become the training signal, AgentJet provides the RL loop, Unsloth provides the
fast fine-tuning backend, and improved local models route away from cloud APIs for familiar
tasks. The Ryzen AI MAX+ 395 with 128GB unified memory is uniquely capable for this — MoE
models like nemotron-3-super (120B total / 12B active) fit entirely in unified memory.
Critical constraints driving the design:
OOM prevention: 128GB is shared CPU+GPU; training + inference models loaded simultaneously
= crash. Must unload inference models before any training job.
Context window management: KV cache grows quadratically with context. A 128K context uses
16x more memory than 32K. Ollama settings + context compression must be first-class.
AMD training gap: Unsloth Studio AMD training is "coming soon" — Phase 1 uses existing
llama.cpp/llamafactory path. Unsloth slots in as a drop-in when AMD support ships.
Architecture
code
COHEZION RUNTIME (online)
CompoundExecutor → JourneyTracker → phi_score + skill_name
JourneyFinetuneConverter → data/training/finetune_journeys.jsonl
│
▼
AGENTJET RL LAYER (src/cohezion/agentjet/)
CohezionWorkflow — wraps CompoundExecutor as AgentJet rollout function
PhiScoreJudger — phi_score → scalar reward (phi×2-1 maps [0.5,1]→[0,1])
JourneyTaskReader — reads existing JSONL (no new data pipeline)
AgentJetTrainer — orchestrates RL loop; manages model unload before training
ContextOptimizer — per-model Ollama settings (num_ctx, flash_attn, rope_scaling)
│
▼
TRAINING BACKEND (phased)
Phase 1 (now): llamafactory + llama.cpp via LocalFinetuner (already exists)
Phase 2 (soon): Unsloth Studio QLoRA when AMD training ships
Both phases: Unsloth Data Recipes (available NOW) for vault→dataset pipeline
│
▼
OLLAMA LOCAL (deployment)
GGUF export → ollama create cohezion-{domain}-v{n}
SmartRouter updated to prefer domain-specialized fine-tuned models
OllamaContextManager ensures models loaded with correct context settings
Model Registry (updated)
Primary fine-tune targets (in priority order for Phase 1):
Model
Size
QLoRA RAM
Domain
Priority
qwen3.5:9b
9B
~8GB train
general, fast iteration
1st
nemotron-3-nano:30b
30B
~24GB train
agentic tasks
2nd
openai/gpt-oss-20b
22B
~16GB train
highest quality/param
3rd
qwen3-coder-next
80B
~64GB train
coding (when headroom allows)
4th
MoE inference models (load via Ollama, NOT fine-tune targets initially):
nemotron-3-super:120b — 12B active params, multi-agent orchestration
glm-5 — 40B active params, reasoning + agentic
minimax-m2.7 — brand new (2026-03-18), agentic/coding
Critical component for OOM prevention and context window efficiency.
python
@dataclass
class ModelContextProfile:
"""Per-model Ollama context settings."""
model_name: str
num_ctx: int # Context window (KV cache driver)
num_gpu: int # GPU layers (-1 = all)
flash_attention: bool # Reduces KV cache ~50%
rope_scaling: str # "linear"|"ntk"|"yarn" for extended ctx
num_parallel: int # Concurrent requests (default 1 during training)
keep_alive: str # "0" during training (unload after use)
CONTEXT_PROFILES: dict[str, ModelContextProfile] = {
"qwen3.5:0.8b": ModelContextProfile("qwen3.5:0.8b", num_ctx=32768, flash_attention=True, ...),
"qwen3.5:9b": ModelContextProfile("qwen3.5:9b", num_ctx=16384, flash_attention=True, ...),
"nemotron-3-nano:30b": ModelContextProfile(..., num_ctx=8192, flash_attention=True, ...),
# Training profiles have reduced ctx to save KV cache memory during training
}
class OllamaContextManager:
"""Apply context profiles to Ollama models via API.
Enforces keep_alive=0 before training to free memory.
Monitors memory pressure (threshold from TierConfig).
"""
def apply_profile(self, model: str, profile: ModelContextProfile) -> None: ...
def unload_all_for_training(self) -> None:
"""Unload ALL inference models before starting training job."""
# Critical OOM prevention: POST /api/generate keep_alive=0 for each loaded model
...
def reload_inference_models(self) -> None:
"""Restore hot/warm tier after training completes."""
...
def get_available_memory_gb(self) -> float:
"""Check available unified memory before training."""
...
def check_oom_risk(self, model_size_gb: float, training_overhead_factor: float = 3.0) -> bool:
"""Return True if loading model for training risks OOM.
training_overhead_factor=3.0: weights + gradients + optimizer states.
"""
...
trainer.py — AgentJetTrainer
python
class AgentJetTrainer:
"""Orchestrates the full CALL RL cycle.
Safety protocol:
1. Check available memory
2. Unload ALL inference models (OllamaContextManager.unload_all_for_training)
3. Run AgentJet RL loop (or llamafactory as Phase 1 fallback)
4. Export GGUF → ollama create
5. Reload inference models
6. Update SmartRouter with new model name
"""
def __init__(
self,
workflow: CohezionWorkflow,
judger: PhiScoreJudger,
reader: JourneyTaskReader,
context_manager: OllamaContextManager,
backend: Literal["agentjet", "llamafactory"] = "llamafactory", # Phase 1 default
): ...
def train(
self,
target_model: str = "qwen3.5:9b",
skill_domain: str | None = None, # None = train on all skills
epochs: int = 3,
min_phi: float = 0.7,
dry_run: bool = False,
) -> TrainingResult: ...
def _safety_check(self, model: str) -> None:
"""Raise if OOM risk detected. Never skip this."""
...
unsloth_bridge.py — UnslothBridge
python
class UnslothBridge:
"""Interface to Unsloth Studio.
Available NOW: Data Recipes API (converts vault content → training datasets)
Available SOON: QLoRA training API (when AMD support ships)
Falls back to LocalFinetuner (llama.cpp) when training not available.
"""
def create_dataset_from_vault(self, vault_query: str) -> Path:
"""Use Unsloth Data Recipes to transform vault notes → JSONL dataset."""
# POST to Unsloth Studio Data Recipes OpenAI-compatible API
...
def train_qlora(self, dataset: Path, model: str, config: dict) -> Path | None:
"""Attempt QLoRA training via Unsloth. Returns None if AMD not supported yet."""
...
def is_training_available(self) -> bool:
"""Check if Unsloth training works on current hardware."""
...
Context Window Optimization Strategy
Key Ollama environment variables to set/expose as Cohezion config:
bash
# In .env or cohezion config:
OLLAMA_FLASH_ATTENTION=1 # 50% KV cache reduction — enable always
OLLAMA_KV_CACHE_TYPE=q8_0 # Quantized KV cache (further memory reduction)
OLLAMA_NUM_PARALLEL=1 # During training: 1 parallel request max
OLLAMA_MAX_LOADED_MODELS=2 # During training: max 2 models (reduce from 4)
The ContextHarness in cohezion/reliability/context_harness.py already does prompt pruning
targeting phi3:mini. Extend it to use per-model ModelContextProfile instead of hardcoded target.
OOM Prevention Protocol (Non-Negotiable)
Before ANY training job, AgentJetTrainer._safety_check() must:
src/cohezion/swarm/model_pool_config.py
- Add new models to hot/warm/cold tier lists
- Add ModelContextProfile registry (or import from agentjet.context_optimizer)
src/cohezion/reliability/context_harness.py
- Extend to accept ModelContextProfile instead of hardcoded "phi3:mini"
src/cohezion/api/__init__.py
- Add POST /agentjet/train endpoint
- Add GET /agentjet/status endpoint
- Add GET /agentjet/models endpoint (lists available training targets)
src/cohezion/skills/AGENTJET_PRIME.md (new PRIME skill definition)
- Training workflow, reward signal design, OOM prevention checklist
pyproject.toml
- Add agentjet to optional deps: [agentjet]
- Add unsloth to optional deps: [unsloth]
Switch from llamafactory to actual AgentJet verl/PPO backend
Multi-skill parallel training (one LoRA per skill domain)
SmartRouter learns to prefer domain-specialized fine-tuned models
Full cross-modal orchestration: task + code + vault all in same embedding space
Verification
bash
# 1. Unit tests (mocked Ollama + AgentJet)
uv run pytest tests/agentjet/ -v
# 2. Context profile dry run (no training)
uv run python -m cohezion.agentjet.trainer \
--target qwen3.5:9b --dry-run --skill coding
# 3. OOM safety check
uv run python -c "
from cohezion.agentjet.context_optimizer import OllamaContextManager
mgr = OllamaContextManager()
print('Available GB:', mgr.get_available_memory_gb())
print('OOM risk for 9B:', mgr.check_oom_risk(18.0)) # 9B × 3x overhead = 27GB
"
# 4. Full pipeline smoke test (synthetic data, 1 epoch, phi3:mini)
uv run python -m cohezion.agentjet.trainer \
--target phi3:mini --epochs 1 --min-phi 0.5 --skill research
# 5. API endpoint test
curl -X POST http://localhost:8080/agentjet/train \
-H "Content-Type: application/json" \
-d '{"target_model": "qwen3.5:9b", "skill_domain": "coding", "dry_run": true}'
# 6. Regression: existing training pipelines still work
uv run pytest tests/flume/ -v
uv run pytest tests/compound/ -v
Platform Resource Manager (Cross-Session)
The problem: Multiple Claude Code sessions, Gemini CLI sessions, background scripts, and
training jobs all compete for 128GB unified memory with no coordination. Each session's
model_pool_manager.py is a singleton that sees only its own allocations. A training job
can OOM the machine while a separate session is serving inference.
The solution: A lightweight persistent resource daemon that acts as the platform's
memory arbiter — any session must check in before loading models or starting training.
New Component: src/cohezion/platform/resource_manager.py
python
Session Usage Pattern
Every new Claude Code / Gemini CLI session that uses Cohezion:
python
# On session start (in CompoundExecutor or via hook)
client = ResourceClient()
await client.register_session(session_id=os.environ["COHEZION_SESSION_ID"])
# Before any model load
if not await client.can_load_model("qwen3-coder-next", size_gb=45.0):
logger.warning("Insufficient platform memory, falling back to nemotron-3-nano:30b")
# Before training (in AgentJetTrainer)
lock = await client.acquire_training_lock("qwen3.5:9b", required_gb=27.0)
if lock is None:
raise ResourceUnavailableError("Training blocked: another session holds training lock")
try:
await self._run_training(...)
finally:
await client.release_training_lock(lock.lock_id)
Usage Pattern Learning
The daemon tracks which models each session uses and how long, building a usage histogram
stored in SurrealDB. This feeds back into model_pool_config.py tier assignments:
python
# Weekly: daemon promotes/demotes models based on actual cross-session usage
# "nemotron-3-nano is used by 80% of sessions for >30min → promote to WARM"
# "qwen3-coder-next last used 14 days ago → demote to COLD"
class TierOptimizer:
def recommend_tier_changes(self, usage_history: list[SessionRecord]) -> list[TierChange]:
"""Data-driven tier assignment based on actual cross-session usage."""
...
async def _safety_check(self, model: str, required_gb: float) -> None:
client = ResourceClient()
if client.is_daemon_running():
lock = await client.acquire_training_lock(model, required_gb, timeout_s=30.0)
if lock is None:
raise ResourceUnavailableError(
f"Cannot train {model}: platform has insufficient memory "
f"or another session holds the training lock"
)
self._training_lock = lock # Released in finally block of train()
else:
# Fallback: local-only check (single-session safety)
state = await OllamaContextManager().get_available_memory_gb()
if state < required_gb * 1.2:
raise OOMRiskError(f"OOM risk: need {required_gb}GB, have {state}GB")
Gemini Embedding 2 — Orchestration Anchor
Gemini Embedding 2 (March 10, 2026) is Google's first natively multimodal embedding model:
maps text, images, video, audio, and documents into ONE unified embedding space.
This upgrades Cohezion's orchestration from keyword matching → semantic concept matching.
Why It Matters
SemanticCache already has a plug-and-play EmbeddingModel interface. The current
FlumeVAEEmbeddingModel uses a 256D SHA-256 hash projection — not truly semantic. Gemini
Embedding 2 slots directly into the same interface as a higher-quality tier.
Three Uses (in priority order)
1. Vault Indexing (offline, one-time cost)
Embed every vault note, decision, pattern, and PRIME skill using Gemini Embedding 2.
Store vectors locally in SurrealDB. Never pay again for the same content.
This makes vault_find_relevant_context() orders of magnitude more accurate.
2. FLUME VAE Distillation (calibration, not runtime)
Use Gemini Embedding 2 vectors as teacher signal to train the FLUME VAE.
The VAE learns to approximate Gemini's embedding quality locally.
After calibration: near-cloud quality at zero API cost per runtime query.
This is knowledge distillation for embeddings — same principle as DistilBERT vs BERT.
3. Cross-Modal Orchestration (when cloud available)
Task descriptions, code snippets, trajectory data, and skill definitions all embedded
into the same space. SmartRouter semantic matching across modalities, not just text.
New Component: src/cohezion/agentjet/embeddings.py
python
class GeminiEmbeddingModel(EmbeddingModel):
"""Cloud Gemini Embedding 2 — uses Gemini API, caches locally.
Never embeds the same content twice. Stores in SurrealDB with content hash key.
Falls back to FlumeVAEEmbeddingModel when cloud unavailable.
"""
def __init__(self, cache_backend: SurrealClient, fallback: EmbeddingModel): ...
async def encode(self, text: str) -> EmbeddingResult:
key = sha256(text)
if cached := await self.cache_backend.get(key): return cached
result = await self._call_gemini_api(text)
await self.cache_backend.store(key, result)
return result
class EmbeddingDistiller:
"""Distills Gemini Embedding 2 quality into local FLUME VAE.
Generates Gemini embeddings for vault corpus, then fine-tunes FLUME VAE
to minimize distance to Gemini vectors. Result: local embeddings that
approximate cloud quality without runtime API calls.
"""
def distill(self, vault_corpus: list[str], epochs: int = 10) -> Path: ...
# Outputs calibrated FLUME VAE checkpoint
class EmbeddingOrchestrator:
"""Selects embedding model based on context and availability.
Routing table:
- Vault indexing (offline): GeminiEmbeddingModel (cloud, cached)
- Runtime inference (online): FlumeVAEEmbeddingModel (local, calibrated)
- Training reward signals: GeminiEmbeddingModel (offline, for distillation)
- Fast routing (hot path): DistilledEmbeddingModel (hash fallback, <1ms)
"""
def get_model(self, context: str) -> EmbeddingModel: ...
Integration Points
SemanticCache.__init__: Accept EmbeddingOrchestrator as embedding_model param
(already supports custom embedding_model injection — zero interface change)
TrajectorySearchEngine.find_similar_trajectories(): Replace hash embeddings with
calibrated FLUME VAE (post-distillation) for better trajectory matching
vault_find_relevant_context(): Use GeminiEmbeddingModel for vault indexing pass
SkillSelector.select_skills(): Use calibrated embeddings for semantic skill matching
Cost Control
Gemini Embedding 2 is API-based (cloud). Usage rules:
ONLY call for novel content (not seen before, per SurrealDB content-hash cache)
NEVER call during runtime execution (FLUME VAE handles runtime)
Batch vault indexing runs offline (configurable schedule, not per-request)
Circuit breaker: if Gemini API unavailable, fall back to FLUME VAE silently
If you need specific details from before exiting plan mode (like exact code snippets, error messages, or content you generated), read the full transcript at: /home/mike-anderson/.claude/projects/-home-mike-anderson-dev-cohezion/fa51e7c9-e669-4877-ac89-6ff357f6ba35.jsonl
If this plan can be broken down into multiple independent tasks, consider using the TeamCreate tool to create a team and parallelize the work.
Assistant
I'm using the executing-plans skill to implement this plan.
Since we're in Claude Code with subagent support available, let me switch to the subagent-driven approach.
Assistant
I'm using the using-git-worktrees skill to set up an isolated workspace.
Assistant
The anthropic-delivery submodule has internal untracked content — that's a submodule-level issue unrelated to our work. I'll create the worktree manually.
Assistant
While the baseline tests run, let me explore the existing codebase to understand the structure.
★ Insight ─────────────────────────────────────
This plan creates a clean closed-loop learning system: execution → phi_score → training signal → improved weights → better execution. The key design insight is using the existing JourneyTracker phi_scores as the reward signal rather than building a new reward system — this means zero additional data labeling overhead.
─────────────────────────────────────────────────
Assistant
Good — platform/ already exists with charter compliance infrastructure. We'll extend it with the new resource management files. Let me now check the key existing files I need to understand before creating the tasks:
Assistant
Tests still running (3,200+ takes ~90s). Let me create the task list and proceed.
★ Insight ─────────────────────────────────────
The plan uses a phased architecture: Phase 1 uses llamafactory as the training backend (already exists via LocalFinetuner), and Phase 2 slots in Unsloth QLoRA when AMD support ships. This is a deliberate adapter pattern — the AgentJetTrainer decouples the RL loop from the specific training backend, so switching backends requires zero changes to the caller.
─────────────────────────────────────────────────
Assistant
Now let me set up task dependencies and start implementing. Tasks 1 (core), 5 (platform), 6 (embeddings), 7 (PRIME skill), and 8 (context_optimizer) can run in parallel. Task 2 (trainer) needs 1 + 8. Task 4 (tests) needs all agentjet files. Task 3 (integrations) needs 8 for ModelContextProfile.
Assistant
Now I'll dispatch subagents for the independent tasks in parallel: Task 1 (AgentJet core), Task 5 (Platform resource management), Task 6 (Embeddings), Task 8 (Context optimizer), and Task 7 (AGENTJET_PRIME skill).
Assistant
Now dispatching 5 parallel subagents for the independent tasks.
★ Insight ─────────────────────────────────────
The subagent-driven approach shines here: each agent gets exactly the context it needs — no more, no less. The context optimizer agent only needs to know about TierConfig and ContextHarness. The core agent only needs CompoundExecutor and JourneyTracker. This laser-focus prevents the context pollution that degrades code quality in long single-session implementations.
─────────────────────────────────────────────────
Assistant
5 parallel agents are running. Let me check the baseline test results while they work.
Assistant
The 5 parallel agents are actively creating the foundation. Let me check on their progress while preparing the trainer.py specification.
★ Insight ─────────────────────────────────────
The CALL architecture reuses the existing JourneyToFinetuneConverter JSONL output as the training data source. This is a key zero-cost data pipeline insight: every execution that runs through CompoundExecutor already produces a phi_score and trajectory. The JourneyTaskReader simply reads that already-generated data — no additional annotation work needed.
─────────────────────────────────────────────────
Assistant
All 5 agents are actively working. The logs show they're reading the codebase and writing files. Let me wait for their completions.
Assistant
Baseline established: 4,271 passing, 27 failing, 26 skipped. The 27 pre-existing failures are our regression baseline — we must not add to them. Now let me wait for the agent completions.
Assistant
Context optimizer complete — DONE. The __init__.py was also created as a side effect. Let me wait for the remaining 4 agents.
Assistant
AGENTJET_PRIME.md complete — DONE. Waiting for the remaining 3 agents (core modules, platform resources, embeddings).
Assistant
Embeddings complete — DONE (338 lines, justified overage due to SurrealDB protocol verbosity). Waiting for the final 2 agents.
Assistant
AgentJet core complete — DONE. Now Tasks 1 (core) and 8 (context_optimizer) are both done, unblocking Task 2 (trainer). Let me dispatch it now while waiting for the platform agent.
Assistant
Trainer agent dispatched. Still waiting for the platform resources agent. Let me check its progress.
I notice the result mentioned src/cohesion/platform/session_tracker.py (typo: "cohesion" instead of "cohezion"). Let me verify the actual path.
Assistant
All 3 new platform files in the correct location. Task 3 (integrations) is now unblocked — dispatching it now while the trainer agent finishes.
Assistant
Two agents running in parallel: trainer and integrations. Once the trainer completes, tests can be dispatched. Waiting for notifications.
Assistant
Trainer complete — DONE. All dependencies for Task 4 (tests) are now resolved. Dispatching the test agent now.
Assistant
Tests agent dispatched. Two agents now running in parallel: integrations and tests. Waiting for completions.
★ Insight ─────────────────────────────────────
The test suite uses pure unittest.mock rather than specialized libraries like aioresponses. This is a deliberate choice for the Cohezion codebase — the CLAUDE.md shows @patch("cohezion.swarm.compound_client.get_compound_client") as the preferred mocking pattern. Mocking at source (the module that creates the client) rather than the underlying HTTP layer makes tests more stable across aiohttp version changes.
─────────────────────────────────────────────────
Assistant
Integrations complete — DONE. All 4 integration changes applied, including the 6 new models across tiers, ContextHarness extension, 3 API endpoints, and pyproject.toml optional deps. Waiting for the tests agent.
Spec compliance review — verify implementation matches the plan exactly
Full regression test — run the 4,271-test baseline to catch any regressions (baseline: 27 pre-existing failures)
Worktree sync — merge spec/call back to main branch via cz worktree sync call
Restore stash — git stash pop to restore your pre-existing work
The tests agent is running the tests/agentjet/ suite. Waiting on it now.
Assistant
All 8 tasks complete! 61/61 AgentJet tests passing, 199/199 platform tests still passing. Updating task 4 and moving to spec compliance review + full regression run.
Assistant
Now running the full regression suite and dispatching the spec compliance review in parallel.
★ Insight ─────────────────────────────────────
Running 61 targeted tests passed, but the full 4,271-test baseline catches cross-module interactions the targeted tests miss — things like singleton pollution in conftest.py (FLUME VAE, RL policy resets) or import-order side effects from the new cohezion.agentjet package being importable. This is why baseline regression after targeted testing is non-negotiable.
─────────────────────────────────────────────────
Assistant
Full regression and spec review both running. Waiting for results.
User
What can we do while we're waiting?
Assistant
Good timing! There's one known gap the spec reviewer will flag: the offline vault indexing script (scripts/index_vault_embeddings.py). This was listed in the Phase 1 checklist but no agent implemented it since it's a standalone script, not a module. I can create it now — it's completely independent of the running agents.
Also, I can restore your stashed work since it's safe: the changes are in .worktrees/call, not in the main working directory.
Want me to:
Create the vault indexing script now (fills the known gap)
git stash pop to restore your pre-existing work while we wait
Both are safe to do while the regression and review agents run.
User
Continue
Assistant
★ Insight ─────────────────────────────────────
The vault indexing script is a one-time offline process: it iterates every vault note, calls Gemini Embedding 2 (once per unique content hash), stores vectors in SurrealDB, and never pays for the same content again. This is the "pay once, use forever" caching strategy that makes the runtime FLUME VAE distillation viable.
─────────────────────────────────────────────────
Assistant
The vault indexing script was created successfully. The stash pop partially failed — the untracked files already exist on disk (likely from another parallel session), but the stash is still preserved (git stash list will show it). Your tracked file changes (cache/swarm files, etc.) were restored. The untracked research files were already present, so nothing was lost.
Summary of what just happened:
✅ scripts/index_vault_embeddings.py created (fills the known spec gap)
⚠️ Stash pop failed on untracked files (already exist) — stash safely preserved, run git stash drop when you've confirmed you don't need it
Still waiting on the regression results and spec review. Both should complete soon.
Assistant
Spec review is PARTIALLY COMPLIANT. Two gaps to fix:
Vault indexing script — Already fixed (just created scripts/index_vault_embeddings.py)
agentjet/__init__.py missing exports — OllamaContextManager, ModelContextProfile, GeminiEmbeddingModel, EmbeddingOrchestrator, CONTEXT_PROFILES not in __all__
Let me fix the __init__.py export gap now.
Assistant
Need to run from the worktree since that's where the new package lives:
Assistant
All 11 exports confirmed. Now let me check the regression results:
Assistant
Regression still running. Both spec gaps are now resolved:
✅ agentjet/__init__.py — all 11 public symbols now exported (18 profiles registered)
The spec review verdict upgrades from PARTIALLY COMPLIANT → FULLY COMPLIANT once regression confirms no regressions.
User
Verdict: PARTIALLY COMPLIANT
All implementation code is present and correct. The one confirmed gap is the offline vault indexing script (acknowledged in the checklist as not done). The __init__.py export surface is narrower than the "all 7 components" description would suggest — the embeddings and context optimizer classes are accessible but not re-exported. Everything else — safety protocol, training profiles, model registry, API endpoints, tests, systemd unit — fully matches spec.
<total_tokens>91522</total_tokens><tool_uses>30</tool_uses><duration_ms>134731</duration_ms>
Full transcript available at: /tmp/claude-1000/-home-mike-anderson-dev-cohezion/fa51e7c9-e669-4877-ac89-6ff357f6ba35/tasks/a42a441637dcfdda9.output
User
Minor Concern
⚠️ agentjet/__init__.py — OllamaContextManager, ModelContextProfile, GeminiEmbeddingModel, EmbeddingOrchestrator, and CONTEXT_PROFILES are not in __all__. They are importable via their submodule paths (from cohezion.agentjet.context_optimizer import ..., from cohezion.agentjet.embeddings import ...) but are not part of the declared public API of the package. This is a minor surface-area gap, not a functional gap.
User
Known Gap (Pre-flagged)
❌ Offline vault indexing script using Gemini Embedding 2 — Not implemented. The checklist item was for a standalone script (e.g., scripts/index_vault_gemini.py) that would batch-index vault content using GeminiEmbeddingModel and store results in SurrealDB. No such script exists in scripts/. The EmbeddingOrchestrator and GeminiEmbeddingModel infrastructure is in place, but the offline indexing driver script that would invoke it is absent.
User
Tests
✅ tests/agentjet/__init__.py — Present.
✅ tests/platform/__init__.py — Present.
✅ tests/agentjet/ — 6 test files present with substantive content:
test_context_optimizer.py (98 lines)
test_embeddings.py (196 lines)
test_judger.py (97 lines)
test_task_reader.py (148 lines)
test_trainer.py (178 lines)
test_workflow.py (130 lines)
tests/platform/ also has relevant tests including test_resource_manager.py (346 lines) and test_tier_optimizer.py (222 lines).
The spec mentioned "6 new models" — this has 12 total entries (likely more were added than the minimum spec). This passes.
✅ src/cohezion/reliability/context_harness.py — ContextHarness.__init__ now accepts profile: ModelContextProfile | None = None. When provided, _get_dynamic_limit() uses profile.num_ctx * 4 as the base limit. TYPE_CHECKING guard avoids circular import.
User
AgentJet Module
⚠️ src/cohezion/agentjet/__init__.py — Exports 6 of the 7 components: AgentJetTrainer, CohezionWorkflow, JourneyTaskReader, PhiScoreJudger, TrainingResult, UnslothBridge. Missing from __all__: OllamaContextManager, ModelContextProfile, GeminiEmbeddingModel, EmbeddingOrchestrator, CONTEXT_PROFILES — none of the context optimizer or embeddings module classes are re-exported. The files exist and are importable directly, but the module's public surface as declared in __init__.py is incomplete. Whether this is a spec violation depends on whether the spec required all 7 components to be exported vs. merely present as submodules.
✅ src/cohezion/agentjet/workflow.py — CohezionWorkflow present. Wraps CompoundExecutor, uses JourneyTracker for phi_score, returns (output, metadata) tuple with phi_score, coherence, success, duration.
✅ src/cohezion/agentjet/task_reader.py — JourneyTaskReader present. Loads from JSONL, falls back to ExperienceCollector. Normalizes both schemas. read() and group_by_skill() present.
✅ src/cohezion/agentjet/context_optimizer.py — OllamaContextManager, CONTEXT_PROFILES, and ModelContextProfile all present. Training profiles use num_ctx=2048 and keep_alive="0" (confirmed in _training() helper). Training variants defined for qwen3.5:9b, nemotron-3-nano:30b, phi3:mini.
✅ src/cohezion/agentjet/trainer.py — AgentJetTrainer and TrainingResult present. backend="llamafactory" is the Phase 1 default. Safety protocol order confirmed:
OOM check (_safety_check) — tries ResourceClient daemon first, falls back to local Ollama poll
Unload all inference models (unload_all_for_training)
Training backend (_run_training)
Reload inference models in finally block — always executes even on failure
Lock release also in finally
✅ src/cohezion/agentjet/unsloth_bridge.py — UnslothBridge present. Phase 1: Data Recipes API (available now). Phase 2 QLoRA: is_training_available() returns False for AMD. Falls back to LocalFinetuner.
✅ src/cohezion/agentjet/embeddings.py — GeminiEmbeddingModel with content-hash SurrealDB cache present. EmbeddingOrchestrator routes by EmbeddingContext (VAULT_INDEXING → Gemini, RUNTIME → FLUME VAE). Circuit breaker (3 failures). FlumeVAEEmbeddingModel and EmbeddingDistiller also present.
User
Platform Layer
✅ src/cohezion/platform/resource_manager.py — All four exports present: ResourceDaemon, ResourceClient, PlatformMemoryState, TrainingLock. Full HTTP daemon with lock management, Ollama polling, fallback to local poll when daemon is down. OOMRiskError and ResourceUnavailableError included.
✅ src/cohezion/platform/session_tracker.py — SessionRecord and SessionTracker both present with usage histogram, session penetration, and get_recent_sessions.
✅ src/cohezion/platform/tier_optimizer.py — TierOptimizer and TierChange present. Three rules implemented: training-only → demote to cold, high-traffic → promote, unused >14 days → demote.
✅ scripts/start_resource_daemon.sh — Executable (-rwxrwxr-x). Checks for already-running daemon via health probe, then runs uv run python -m cohezion.platform.resource_manager.
✅ scripts/cohezion-resources.service — Valid systemd unit. Restarts on failure, routes logs to journal, targets correct entry point.
The implementation is clean. Time to commit and sync the worktree back.
Assistant
29 files staged — exactly what was planned. Now committing and syncing back to main.
Assistant
Committed — 29 files, 5,190 insertions. Now syncing back to the base branch:
Assistant
The partial stash pop left pyproject.toml and uv.lock modified on the main branch. Need to stash them temporarily, sync, then pop.
Assistant
The Phase 1 implementation completed in the previous session. Let me update the plan file to reflect the completed status before exiting plan mode.
Assistant
★ Insight ─────────────────────────────────────
The CALL Phase 1 implementation introduced a key architectural pattern worth noting: the three-layer fallback chain appears across multiple components — GeminiEmbeddingModel falls back to FlumeVAEEmbeddingModel, AgentJetTrainer's safety check falls back from ResourceClient to local OllamaContextManager, and UnslothBridge falls back to LocalFinetuner. This isn't accidental — it reflects the system's "graceful degradation" principle where cloud/daemon dependencies are optional, not required, keeping the system functional even when external services aren't running.
─────────────────────────────────────────────────
Phase 1 is fully complete and merged to gemm-hip-cpp-fused. Summary of what was delivered:
class ResourceDaemon:
"""Persistent platform resource arbiter.
Runs as background process between sessions.
Polls Ollama /api/ps for ground-truth model state.
Manages training locks to prevent concurrent training OOM.
Start: uv run python -m cohezion.platform.resource_manager
Or via systemd: cohezion-resources.service
"""
POLL_INTERVAL_S = 30 # Ollama /api/ps poll frequency
PORT = 8765 # Local HTTP API port
TRAINING_LOCK_TTL_S = 7200 # Max training job reservation = 2 hours
async def poll_ollama_state(self) -> OllamaState:
"""Query /api/ps for actual loaded models + memory usage."""
...
async def get_available_memory_gb(self) -> float:
"""Total unified memory - Ollama usage - OS overhead - 10GB safety buffer."""
...
async def request_training_lock(
self, session_id: str, model: str, required_gb: float
) -> TrainingLock | None:
"""Exclusive lock for training. Returns None if insufficient memory.
Locks are stored in SurrealDB with TTL for crash recovery.
"""
...
async def release_training_lock(self, lock_id: str) -> None: ...
async def register_session(self, session_id: str) -> None:
"""Track active sessions for cleanup on death."""
...
async def cleanup_dead_sessions(self) -> None:
"""Release locks from sessions that died without cleanup."""
...
class ResourceClient:
"""Lightweight client for any session to consult the ResourceDaemon.
Falls back gracefully if daemon not running (single-session mode).
All sessions MUST use this before loading large models or training.
"""
DAEMON_URL = "http://localhost:8765"
async def check_memory(self) -> PlatformMemoryState:
"""Get current memory state across all sessions."""
...
async def acquire_training_lock(
self, model: str, required_gb: float, timeout_s: float = 30.0
) -> TrainingLock | None:
"""Request exclusive training access. Blocks until available or timeout."""
...
async def can_load_model(self, model_name: str, size_gb: float) -> bool:
"""Check if loading a model is safe given all sessions' current usage."""
...
def is_daemon_running(self) -> bool:
"""Silent check — False = fall back to local-only mode."""
...
@dataclass
class PlatformMemoryState:
total_gb: float # 128 for Ryzen AI MAX+ 395
ollama_used_gb: float # From /api/ps (all sessions combined)
system_reserved_gb: float # OS + non-Ollama processes
training_reserved_gb: float # Active training lock reservations
available_gb: float # total - ollama_used - system_reserved - training_reserved
safety_buffer_gb: float = 10.0 # Never let available drop below this
loaded_models: list[str] # All models currently loaded across ALL sessions
@dataclass
class TrainingLock:
lock_id: str
session_id: str
model: str
reserved_gb: float
acquired_at: float
expires_at: float # TTL for crash recovery