Orchestrata Ultimate › Plans › context-injection-improvement-plan
Context-Injection Improvement Plan
Source: plans/context-injection-improvement-plan.md at 8a2cb42ad · last changed 2026-07-27 · first committed 2026-07-13 · 149 lines.
Prose pending.
Plan text
Context-Injection Improvement Plan
1. Current state
The repository has a layered context-injection architecture:
sources → UnifiedContextAssembler → ContextBudget/Usage → volk prompt
Live sources today:
- KG code context (
src/orchestrata_ultimate/knowledge_graph/context_injector.py) for subjects inINJECT_SUBJECTS. - Task-type packs (
src/orchestrata_ultimate/knowledge_graph/context_pack/) via SPEC-106. - Memory (
src/orchestrata_ultimate/memory/) — recall + summary perthread_id. - Prior-stage artifacts (
src/orchestrata_ultimate/orchestrator/artifact_store.py).
Dead/unused sources today:
- Session/goal context —
mission_context.render_mission_context()exists but production passescontext_data=None(src/orchestrata_ultimate/kernel/pipeline_kg.py:506). - Plan window —
ContextAssembly.parts["plan"]is budgeted but never populated (src/orchestrata_ultimate/context/assembler.py:112). - Semantic graph (
src/orchestrata_ultimate/semantic_graph/) — ingested, tested, but not injected at runtime. - Serialized AST (
plans/ast-ultimate.json,scripts/serialize_codebase_ast.py) — regenerated manually, never read by live context injection.
2. Problems to solve
- Session continuity is broken. Volks have no compact view of the active goal, pending work, latest handoff, or project state.
- Memory recall is O(N).
RedisMemoryStore.retrieve_by_scope()can load up to 1000 entries and score them in Python. - Rich data is not pulled automatically. Previous experiments showed models did not voluntarily use AST/graph data; it must be injected for them.
- Context budgets are not observed.
ContextUsage.to_dict()exists but is not logged, so token spend per layer is invisible. - Artifact store is in-memory only. Long runs lose artifacts if the process restarts, and digests are not paginated.
- Schema drift complicates KG queries (
VolkvsAgent,ClassvsCodeClass, etc.).
3. Plan of work (in order)
Phase 0 — Instrumentation and quick fixes
Goal: make the existing assembler observable and stop losing session context.
-
Wire session context into the assembler
- File:
src/orchestrata_ultimate/kernel/pipeline_kg.py - Action: pass a real
ContextDataobject into_assemble_context_for_subjectinstead ofNone. - Seams:
PipelineRunneralready carries asession_controller; expose a method to loadContextData.src/orchestrata_ultimate/session/cli/pipeline.pyshould pass controller context into the runner.
- Test: add an observed test asserting the mission layer is non-empty when a session has active goals.
- File:
-
Populate the plan layer
- File:
src/orchestrata_ultimate/context/assembler.py - Action: add a
plan_contextprovider that renders the next planned stages / recent outcomes from the pipeline result. - Budget: use the existing 600-token
planreservation.
- File:
-
Log context usage per call
- File:
src/orchestrata_ultimate/kernel/pipeline_kg.py - Action: after
assembler.assemble(), logassembly.usage.to_dict()at INFO. - This creates the data needed to optimize budgets later.
- File:
-
Cap memory recall cost
- File:
src/orchestrata_ultimate/memory/hot_store.py/memory_engine.py - Action: add a
max_age_seconds/max_entriespre-filter before vector scoring; default to the most recent 200 entries or 24h. - Keep the existing similarity logic; just score fewer entries.
- File:
Phase 1 — Make AST and graph data reachable
Goal: stop expecting the model to pull data; push the right data into the prompt.
-
Bridge AST serializer into Neo4j / KG context ✅
- Files:
scripts/serialize_codebase_ast.py,src/orchestrata_ultimate/knowledge_graph/kg_context.py - Action:
- Added
serialize_codebase_ast.py ast-to-kgsubcommand that writes complexity, branch_count, and CALLS edges fromplans/ast-ultimate.jsononto existing:Functionnodes. - Extended
KGCodeContextwithget_complexity_hotspots()andget_call_graph_neighborhood()to query these signals.
- Added
- Injection:
ast_contextpart already exists inContextAssembly(budget 500 tokens).
- Files:
-
Wire semantic graph into context injection
- Files:
src/orchestrata_ultimate/semantic_graph/,src/orchestrata_ultimate/context/providers/ - Action:
- Create
SemanticGraphContextProviderthat callssemantic_graph.retrieve(query_embedding). - Add a
semanticlayer toContextAssembly(budget 800 tokens) and enable it whensubjectisimplement,fix_issues, orreview_and_test.
- Create
- This directly fixes the "model did not pull data" failure mode.
- Files:
-
Enable Prolog relevance refinement by default
- File:
src/orchestrata_ultimate/kernel/pipeline_kg.py - Action: construct a
KgRelevanceRetrieverwhen aPrologBridgeis available and pass it toContextInjector.
- File:
Phase 2 — Quality and scale
Goal: make context injection reliable for long-running sessions and large codebases.
-
Adaptive pack trimming
- File:
src/orchestrata_ultimate/context/assembler.py - Action: when a layer exceeds its budget, truncate by sentence/paragraph boundaries rather than hard string slicing; prioritize mission/plan/user, then graph, then memory.
- File:
-
Project-scoped context ✅
- Files:
knowledge_graph/project_resolver.py,context_injector.py,context_assembler.py,context_providers/ast_context.py,kernel/pipeline_kg.py - Action: centralize project-id resolution in
resolve_project_id(KG Project-node lookup first, basename fallback); threadproject_idthrough AST context rendering and the semantic-layer requirement/decision queries; replace repeated basename extractions inpipeline_kg.py.
- Files:
-
Incremental KG sync ✅
- File:
src/orchestrata_ultimate/knowledge_graph/synchronizer.py - Action:
ensure_freshandsync_projectnow load and save per-file hash state from.orchestrata/kg_sync_state.json, so incremental sync survives process restarts and only changed files are re-synced.
- File:
Phase 3 — Schema and unification
Goal: one canonical KG schema so context queries are simple and fast.
-
Canonicalize KG labels
- Pick one label per concept (
Volk/Agent,Class/CodeClass,Spec/Specification,Requirement/RequirementItem). - Update
sync.py,Neo4jSyncer, and all query modules. - Retire defensive coalescing in
context_injector.py.
- Pick one label per concept (
-
Unify context under a single query interface
- File:
src/orchestrata_ultimate/knowledge_graph/query_engine.py - Action: make
QueryEnginethe one entry point used byContextInjector; movevolk_work_context,run_provenance, and semantic retrieval behind it.
- File:
Phase 4 — Artifact store refactor (user backlog)
Goal: durable, queryable artifacts that survive restarts and support richer digests.
-
Persist artifacts to disk / Neo4j
- File:
src/orchestrata_ultimate/orchestrator/artifact_store.py - Action:
- Add an
output_dirconstructor argument; write each artifact to a timestamped JSONL file. - On load, replay the JSONL into the in-memory index.
- Keep the existing in-memory API unchanged.
- Add an
- File:
-
Paginated / ranked digest rendering
- File:
src/orchestrata_ultimate/context/providers/artifact_digest.py - Action:
- Rank artifacts by recency and relevance to the current subject.
- Render only the top-N within the artifact budget instead of dumping every prior artifact.
- File:
-
Trace-aware artifact indexing
- Add
spec/reqsfields toPipelineArtifact. - Index by requirement so a volk working on
REQ-025-091can retrieve prior artifacts that trace to it.
- Add
4. Definition of done
- [ ] Session context is non-empty in production runs.
- [ ] Plan layer is populated.
- [ ] Context usage is logged for every volk call.
- [ ] Memory recall is capped (time or count) and tests prove it.
- [ ] Semantic graph context is injected for at least
implement/fix_issues/review_and_test. - [ ] AST-derived signals (complexity, call graph) are queryable from the KG and injected.
- [ ] Artifact store is persistent across restarts.
- [ ] All changes have observed tests; no mocks; no pytest-xdist.
5. Risks and blockers
- Schema unification is a breaking change for the Neo4j KG; requires a migration or full re-sync.
- Semantic graph depends on Memgraph being up; fallback to no-op if unavailable.
- AST-to-KG bridge may double sync time; make it incremental and optional first.
- Artifact store persistence needs a stable
output_dirconvention across CLI, kernel, and gateway paths.