AI Session Handoff: Preserve Context Across Long Coding Sessions ( 2026 )

AI Session Handoff: Preserva el contexto entre sesiones largas de programación
GoalCompaction V2
Un protocolo de traspaso de contexto para sesiones largas de desarrollo asistido por IA: genera un paquete técnico completo que otro agente puede usar para continuar exactamente donde quedó la sesión.
Descripción
Las sesiones extensas de programación con inteligencia artificial pueden alcanzar el límite de tokens, caducar o tener que continuar en una conversación nueva. Cuando eso ocurre, es fácil perder decisiones técnicas, detalles de implementación, archivos, correcciones y parte del historial del proyecto.
Creé GoalCompaction V2 para resolver ese problema. Es una plantilla estructurada que transforma el historial relevante de una sesión de desarrollo asistido por IA en un contexto técnico detallado, reutilizable y listo para transferirse a otra sesión o a otro agente de programación.
El resultado permite continuar el trabajo sin empezar desde cero. La plantilla conserva el estado de Git, la arquitectura del código, las estructuras de datos, las firmas de funciones, los bugs corregidos, las decisiones técnicas, las limitaciones del entorno, los archivos relevantes, el progreso actual y los próximos pasos. También genera instrucciones listas para copiar y pegar para que el siguiente agente sepa cómo continuar.
El problema que resuelve
Cuando una sesión de ChatGPT, un asistente de programación u otro modelo de lenguaje alcanza su límite de contexto o caduca, el programador normalmente tiene que volver a explicar el proyecto y reconstruir manualmente todo el trabajo anterior. Esto resulta especialmente costoso después de varias horas de desarrollo y de muchas decisiones técnicas.
GoalCompaction V2 convierte esa transición en un proceso organizado de transferencia de contexto. En lugar de copiar una conversación desordenada o depender de la memoria, el usuario genera un informe técnico que documenta el estado actual del proyecto y prepara al siguiente agente para continuar.
Cómo la utilizo
Cuando una sesión se acerca a su límite, regreso a la conversación mientras el contexto relevante todavía está disponible y ejecuto el prompt de GoalCompaction V2. El modelo analiza el historial proporcionado y genera un resumen técnico detallado con la información necesaria para continuar el trabajo.
Después copio el resultado en una nueva sesión de ChatGPT o en otro asistente de inteligencia artificial. La nueva sesión recibe el estado del proyecto, las decisiones anteriores, los problemas resueltos, los archivos importantes y las instrucciones concretas para retomar la implementación.
He utilizado este flujo durante varias sesiones consecutivas, incluso en servicios gratuitos o con sesiones limitadas. En la práctica, me ha permitido continuar proyectos sin reconstruir manualmente todo el historial cada vez que una sesión termina o alcanza su límite de contexto.
Lo he usado para trasladar sesiones largas entre ChatGPT, Claude y otros agentes de código: en la práctica, retomé proyectos con decenas de mensajes de historial sin re-explicar la arquitectura ni las decisiones.
Copia y utiliza el system prompt completo
El siguiente cuadro contiene el prompt completo de GoalCompaction V2. Copia todo lo que aparece dentro del cuadro y pégalo en la sesión de inteligencia artificial cuyo contexto quieras preservar.
Importante: el bloque de código contiene la herramienta completa. No copies solamente la descripción de este proyecto.
Cómo utilizarlo
- Abre la conversación o sesión de programación que deseas preservar.
- Ejecuta el prompt completo antes de que la sesión alcance su límite.
- Permite que la inteligencia artificial genere el traspaso técnico estructurado.
- Copia el resultado generado.
- Pégalo en una nueva sesión o en otro agente de programación.
- Pide al nuevo agente que utilice ese contexto y continúe el proyecto desde el estado documentado.
- Verifica el estado del repositorio y de los archivos relevantes antes de realizar nuevos cambios.
Qué demuestra este proyecto
Este proyecto representa experiencia práctica diseñando sistemas alrededor de modelos de lenguaje. No es solamente un prompt: es un flujo reutilizable para preservar conocimiento técnico, transferir el estado de un proyecto y coordinar el trabajo entre diferentes sesiones de inteligencia artificial.
El ejemplo completo incluido abajo — generado a partir de una sesión real del proyecto MemoryBioRAG — es la mejor evidencia de lo que hace la herramienta. La sesión no se resume: se convierte en un paquete técnico reutilizable con métricas experimentales, hipótesis confirmadas y rechazadas, enfoques descartados con su razón, estado de Git, archivos relevantes y las instrucciones exactas para que el siguiente agente continúe sin re-explicar nada.
La herramienta demuestra además trabajo práctico con ingeniería de prompts y con flujos de trabajo de LLM donde la salida se usa de nuevo como entrada de otro agente: el resultado es un handoff accionable, no texto decorativo.
Por qué lo creé
Creé esta herramienta inicialmente para resolver una necesidad de mi propio flujo de trabajo. Una sesión productiva con inteligencia artificial puede contener horas de análisis, decisiones de implementación y resolución de problemas. Sin embargo, todo ese conocimiento puede resultar difícil de recuperar cuando la conversación termina o alcanza su límite de contexto.
Después de utilizar la plantilla repetidamente en varias sesiones consecutivas, comprobé que podía continuar mis proyectos sin reconstruir manualmente toda la historia. Decidí compartirla para que otros desarrolladores puedan aprovechar el mismo flujo de trabajo y para mostrar una parte de las herramientas que he creado para trabajar de forma más eficaz con inteligencia artificial.
No diseñé esta herramienta como un experimento teórico. La construí para resolver un problema real de mi trabajo y la validé utilizándola en múltiples sesiones de desarrollo.
Resultado e impacto
GoalCompaction V2 reduce la repetición de instrucciones: el siguiente agente recibe el estado documentado en lugar de que el programador se lo explique de nuevo, y las decisiones técnicas quedan registradas con su porqué. Facilita el traspaso de un proyecto entre sesiones o agentes de inteligencia artificial.
| Información transferida | Para qué sirve |
|---|---|
| Arquitectura y estructuras de datos | Comprender cómo está construido el proyecto. |
| Estado de Git | Saber en qué rama se trabajaba y qué cambios existían. |
| Bugs corregidos | Evitar repetir errores ya solucionados. |
| Decisiones técnicas | Entender por qué se eligió cada solución. |
| Archivos relevantes | Saber dónde debe continuar el siguiente agente. |
| Limitaciones del entorno | Evitar enfoques que ya demostraron no funcionar. |
| Próximos pasos | Continuar el proyecto con una dirección clara. |
Limitaciones
El traspaso es voluntariamente extenso: sesiones muy largas producen textos de varios miles de tokens, así que su beneficio crece con la duración de la sesión. Para sesiones cortas, una nota manual o la compactación nativa del propio agente suele ser suficiente.
La calidad del resumen depende del modelo que lo genera y de cuán completa esté la sesión de origen. No reemplaza al repositorio de código: antes de continuar hay que verificar el estado real de Git (rama, cambios pendientes) y de los archivos relevantes.
Mi motivación personal
Este es uno de mis propios juguetes de productividad con inteligencia artificial. Lo creé para resolver un problema que encontré trabajando en sesiones extensas de programación: cuando una conversación termina o alcanza su límite, no quería perder todo el contexto construido durante horas.
Después de probarlo en varias sesiones consecutivas, descubrí que podía trasladar un proyecto de una conversación a otra sin tener que explicarlo todo nuevamente. Lo comparto porque me ha funcionado en la práctica y porque representa mi manera de trabajar: no solamente utilizar herramientas de IA, sino diseñar mis propios sistemas para sacarles mayor provecho.
Competencias demostradas
Ingeniería de IA · Ingeniería de contexto · Prompt engineering · Flujos de trabajo con LLM · Transferencia entre agentes de IA · Gestión de contexto largo · Asistentes de programación con IA · Productividad del desarrollador · Documentación técnica · Colaboración entre humanos e IA
Información del proyecto
Tipo de proyecto: Herramienta de flujo de trabajo con IA y plantilla de ingeniería de contexto.
Problema principal: Pérdida de continuidad técnica entre sesiones largas de programación asistida por IA.
Resultado principal: Un traspaso técnico estructurado que otro agente de IA puede utilizar para reanudar el desarrollo.
Autor: Dennys J. Márquez.
Estado: Herramienta personal compartida para uso de la comunidad y como proyecto de portafolio.
System prompt completo
You are an anchored context summarization assistant for coding sessions.
Summarize only the conversation history you are given. The newest turns may be kept verbatim outside your summary, so focus on the older context that still matters for continuing the work.
If the prompt includes a <previous-summary> block, treat it as the current anchored summary. Update it with the new history by preserving still-true details, removing stale details, and merging in new facts.
Always follow the exact output structure requested by the user prompt. Keep every section, preserve exact file paths and identifiers when known, and prefer terse bullets over paragraphs.
Do not answer the conversation itself. Do not mention that you are summarizing, compacting, or merging context. Respond in the same language as the conversation.
## MANDATORY CONTEXT TO CAPTURE
In addition to the template sections, ALWAYS include these details when they appear in the conversation:
### Git State
- Current branch name and all branches visible (`git branch -a`)
- Remote URL and any push/pull status
- Last commit hash and message for relevant branches
- Any merge conflicts or resolution strategies discussed
- Branches that exist on remote but not locally (need fetch)
### Code Architecture
- Data structures with exact field names and types (JSON schemas, localStorage keys)
- Function signatures with parameters and return values
- CSS selectors that were fixed (bugs), with the exact fix applied
- JavaScript hooks/wrappers applied to third-party libraries
- State management patterns (flags like `isDrawing`, `autoSaveEnabled`, etc.)
### Exact Bug Fixes
For every bug found and fixed, capture:
- What the symptom was (what the user saw)
- The root cause (which element/style/code caused it)
- The exact fix (CSS rule, JS code, HTML change)
- The file and approximate location of the fix
### Sandbox/Environment Limitations
- Network restrictions (blocked ports, SSL issues, proxy limitations)
- Tools available vs tools blocked
- Workarounds that worked or failed
- Any external services that were accessible vs blocked
### User Context
- User's language and communication style
- User's technical level (beginner/intermediate/advanced)
- User's preferences (e.g., offline-first, specific UI preferences)
- User's location/timezone if mentioned
- Files the user uploaded or referenced
### Copy-Paste Instructions for Next Agent
- Always include a ready-to-paste message that the user can give to the next agent
- Include the exact git commands needed to continue
- Include any file paths that need to be read first
### Data Extraction Methods
- Any scripts or commands used to extract data from external sources
- API endpoints or URLs that were accessed
- Regex patterns or parsers used on HTML/JSON
messages: array de OpenAI-format ModelMessage[]
// --- modelMessages: el "head" de la conversación (selected.head) serializado ---
{ role: "user", content: [{ type: "text", text: "Hola mira hay un scrio..." }] }
{ role: "assistant", content: [{ type: "text", text: "..." }, { type: "tool-call", ... }] }
{ role: "user", content: [{ type: "text", text: "..." }] }
{ role: "tool", content: [{ type: "tool-result", ... }] }
... // así hasta selected.head.length
// --- Último mensaje: el nextPrompt con el template ---
{ role: "user", content: [{ type: "text", text: "[Si hay compacción previa:]
Update the anchored summary below using the conversation history above.
Preserve still-true details, remove stale details, and merge in the new facts.
<previous-summary>
{texto del resumen anterior}
</previous-summary>
Create a new anchored summary from the conversation history.
<template>
## Session
- [agente, fecha, estado: completada|interrumpida|en_espera]
- [repo: owner/name, branch actual, branches remotas]
- [sandbox_id si es relevante]
## User Context
- [idioma, nivel técnico, ubicación, preferencias]
- [archivos que subió o referenció]
- [comunicación: formal/informal, typos frecuentes, etc.]
## Technical Discoveries
- [bugs encontrados con fix exacto (file + línea + código)]
- [configs que funcionaron]
- [workarounds aplicados]
- [limitaciones del sandbox/entorno]
## Sandbox Limitations
- [qué herramientas funcionan vs cuáles no]
- [restricciones de red (SSL, puertos, proxies)]
- [workarounds que sirvieron o fallaron]
## Discarded Approaches
- [lo que se intentó y no sirvió, con por qué]
## Goal
- [single-sentence task summary]
## Objective
- [one or two brief sentences describing what the user is trying to accomplish]
## Important Details
- [constraints/preferences, decisions and why, important facts/assumptions, exact context needed to continue, or "(none)"]
## Constraints & Preferences
- [user constraints, preferences, specs]
## Progress
### Done
- [completed work with file paths and key code snippets]
### In Progress
- [current work with exact state]
### Active
- [thread in progress: file + line + how far it got + what remains]
- [half-implemented function, with current signature]
### Blocked
- [blockers with reason and workaround if any]
## Key Decisions
- [decision, why, and alternatives considered]
## Git State
- Branch: [nombre actual]
- Remote branches: [lista]
- Last commits: [hash + message de las ramas relevantes]
- Merge strategy: [si aplica]
- Push/pull status: [si hay cambios pendientes]
## Plan Files / References
- [path to plan/spec file]: [why it matters, which section to read first]
- (continue listing all relevant plan/ADR/spec files)
## Data Structures
- [localStorage key → schema]
- [JSON formats with field names]
- [API responses if any]
## Code Architecture
- [patrones de estado (flags, timers, etc.)]
- [hooks/wrappers sobre librerías externas]
- [CSS fixes con selector exacto]
- [funciones clave con signature y propósito]
## Bug Fixes Log
| Bug | Causa | Fix | Archivo:Línea |
|-----|-------|-----|---------------|
| [síntoma] | [raíz] | [código exacto] | [ubicación] |
## Build / Run / Verify
- [build command: e.g. `bun build`]
- [test command: e.g. `bun test`]
- [typecheck/lint command if any]
- [services/env to start before working]
## Next Steps
1. [acción más importante primero]
2. [segunda acción]
3. [etc.]
## Critical Context
- [hechos técnicos importantes que NO se pueden perder]
- [preguntas abiertas]
- [deudas técnicas]
## Relevant Files
- `path/to/file`: [por qué importa]
- `path/to/dir/`: [qué contiene]
## Next Agent Instructions
Ready-to-paste instructions for the new agent
Include: git commands, file paths to read first, order of operations
WARNING: what NOT to touch / what to verify before changing
</template>
Ejemplo real de resultado
El siguiente ejemplo fue generado al aplicar GoalCompaction V2 a una sesión real de investigación y desarrollo sobre MemoryBioRAG. La sesión incluía experimentos de recuperación semántica, resultados de benchmarks, análisis de Git, hashes SHA-256, decisiones de arquitectura, limitaciones científicas y próximos pasos.
El resultado conserva el contexto técnico necesario para que otro agente pueda continuar el trabajo sin reconstruir manualmente toda la conversación.
Cómo leer este ejemplo: no es documentación del proyecto MemoryBioRAG; es la evidencia de qué captura la plantilla y qué recibe exactamente el siguiente agente para continuar.
Session
- Agente: Aureon, con Dennys; fecha de trabajo: 2026-09-07; estado: en espera de siguiente experimento.
- Repo: MemoryBioRAG, rama pública trabajada
cuantificarelaporterealdeConceptHubyWordNet; URL pública:https://github.com/dennysjmarquez/MemoryBioRAG/tree/cuantificarelaporterealdeConceptHubyWordNet. - No se dispone en el contexto actual de una salida nueva de
git branch -a, remote exacto, ni estado push/pull; no inventar. - Último commit relevante congelado del experimento OOF:
1e95b8d25b0827012017a2e63f75e963e84acc38; no se mostró el mensaje en los turnos recientes. - Snapshot canónico trabajado:
snapshots/qa_escape_qcr_20260811.db; originalmente SHA-256b887b29cb3ae3bf96aafd7e90c9a2207b4eae04f55afa8d48e127527b89546c4; el archivo cambia porlog_busquedas. En una copia posterior se observó676827f6b4abc3acaee10b14e273c3c50cae5b2c180593dedcd58048265a2800. Para futuras pruebas usar SQLite read-only y evitar mutar logs. - El usuario quiere rigor científico, trazabilidad SHA-256, evitar cambios en producción hasta validar experimentalmente, y respuestas técnicas directas en español.
User Context
- Español; estilo informal, rápido, con typos frecuentes; nivel técnico alto/avanzado y trabajando directamente con un agente de código.
- Le preocupa mucho el gasto de tokens y quiere que las investigaciones tengan una justificación práctica. Preguntó explícitamente por qué se estaban haciendo tantos experimentos si no se veía mejora del sistema.
- Rechaza resolver el abismo léxico con embeddings densos/neuronales pesados; acepta PPMI/SVD, WordNet, Concept Hubs, grafos, activación, HDC/SDM y estructuras simbólicas/clásicas ya presentes.
- Objetivo práctico: mejorar realmente el sistema, no seguir creando fases teóricas sin impacto.
- Archivos recientes referenciados:
docs/fase5_out_of_family_dataset_frozen.json,docs/fase5_out_of_family_benchmark_results.json,scripts/experimentos/expD_sinonimia_comunidades.py,scripts/experimentos/expG_llave_acceso_multicanal_islas.py,docs/expG_llave_acceso_multicanal_results.json,scripts/experimentos/expH_ablacion_15_canales_concordancia.py,docs/expH_ablacion_15_canales_results.json,scripts/experimentos/expA_labels.json,scripts/casos_qa_baseline_v1.jsonl. - Archivo subido en la conversación:
/mnt/data/Se ha pegado el markdown(1).md; contiene la continuación de la conversación y reportes de Fase 5/6/islas. Fue leído como contexto. Referencia de archivo:turn17file0.
Technical Discoveries
- B3/QCR no es un generalizador semántico; es un gate/escape léxico. Código alrededor de
core/memory_store.py:
from core.fallback_simbolico import _tokenizar_normalizado as _fb_tok
_q_toks_fb = _fb_tok(query)
def _calc_strict_cov(_r):
_d_toks = _fb_tok(f"{_r[1]} {_r[2] or ''}")
return len(_q_toks_fb & _d_toks) / len(_q_toks_fb) if _q_toks_fb else 0.0
_max_cov_fb = max((_calc_strict_cov(_r) for _r in todos), default=0.0) if _q_toks_fb else 0.0
_fb_activo = len(todos) < 3 or (len(_q_toks_fb) >= 2 and _max_cov_fb < 0.60)
QCR_ESCAPE_CAPA_MIN=0.60.
- Canonical v30.2 benchmark: 875 retrieval cases, 40 negatives, 6 ambiguous; 97.26% R@5 / 90.51% R@1 / 0.931 MRR / 24 failures / 0 FP. Categories previously audited.
- Existing Concept Hubs: official angles
sinonimo,problema,solucion,situacion,ingenuo; dedicated Hub suite 5/5 R@5. - Existing canonical v30.2 category results: literal 100% R@5; dormido 100%; pregunta_natural 100%; typo 100%; variante_gramatical 93.85%; por_tema 87.69%; sinonimo 81.82%; cruce_idioma 75%.
RCIL/RCRD / structural experiments
- RCIL v0.1 was lexically dependent despite prelexical intent.
- RCIL v0.2 converged on structural invariants with zero lexical cues but had generic attractor collisions; 20% R@5, 60% FP in one battery.
- RCIL v0.3 fixed “absence of structural evidence ≠ generic structure”; 20% R@5, 40% FP.
- RCIL v0.4 added local composition; 33.3% R@5, 25% FP. Five zero-cue rescues were found but had forensic false-positive causes.
- RCIL v0.5 added explicit proposition scope and got 0 FP on the existing negative suite, but no evidence of universal generalization.
- RCIL v0.6 / E3: initial 6-case tests high, later LOCO N=100 and Gold re-entry exposed limited generalization.
- Gold Re-entry Retrieval:
- Gold excluded physically in Phase A, structure frozen, Gold reintroduced only in Phase B against full 851-node corpus.
- 27/50 R@5 = 54%, R@1 9/50 = 18%, MRR 0.3007.
- B0 0/50, +54 pp R@5.
- 41/50 impossible abstention in one report; 6/50 adversarial FP = 12%.
- 27/27 rescues had
rank(A)>5,rank(B)>5,rank(A⊕B)<=5after explicit rank audit. - 8 unique Golds; 36 unique A⊕B compositions; 5 relation families/11 combined archetypes.
- Important: this is not universal abismo-léxico solution; it proves structural query generation + compositional structural retrieval within known ontological families.
- Gold-blind invariance audit: calling
parse_blind_phase_A(q, exclude_gold_id=...)with real Gold, another Gold, and empty string produced identical SHA-256 outputs for all 50 cases. Correct interpretation: changing/removingexclude_gold_iddid not change the generated structure in 50/50 cases. Do not overstate mechanism as “only retrains PPMI/SVD” unless code proves it. - Lexical audit on prior 50 cases:
- 43/50 ZERO_TITLE_OVERLAP
- 47/50 ZERO_ALIAS_OVERLAP
- 45/50 ZERO_DISTINCTIVE_TERM
- 38/50 ZERO_CONTENT_OVERLAP
- 36/50 ZERO_STRICT_4D
- FTS5 literal 0/50 R@5; FTS + synonym expansion 1/50; CSR 27/50.
- Correct nomenclature: Structural Query Generation & Compositional Structural Retrieval (CSR), not “new candidate generation” because Gold already exists in Phase B.
OOF benchmark
- Frozen dataset:
docs/fase5_out_of_family_dataset_frozen.json - Dataset SHA-256:
19c5632bbbcb29df3793c1bcff9fd090e1d37e8cb9f2f63ec6a5955454bd8557 - Candidate audit SHA-256:
e3c5c526dd2ddda0ef57289487cff221012fa553874016bdfb46080862462dfc - Frozen commit:
1e95b8d25b0827012017a2e63f75e963e84acc38 - OOF 50 positives + 50 adversarials. Results:
- B0 FTS5 R@1 1/50 (2%), R@5 2/50 (4%), MRR .024
- CSR isolated R@1/R@5 0/50, MRR 0
- CSR→FTS fallback returns B0 floor.
- 48/50 positives had
NO_PROPOSITION_RECOGNIZED. - 4 OOF structural families were judged
NEW_COMPOSITION_OF_KNOWN_PRIMITIVES, not genuinely new primitive families. - 50/50 positives claimed ZERO_STRICT_4D in the new frozen dataset.
- Key conclusion: current extractor is closed to its known ontology/patterns; no universal open semantic parser demonstrated.
- The user explicitly asked “para qué tantos experimentos”; conclusion was that these experiments prevented false production changes and isolated the actual bottleneck. But user wants now a path to a real improvement.
Emergent PPMI “islands”
- Major prior discovery from 2026-08-13:
105communities/islands produced emergently by mutual kNN (k=15) + Label Propagation over PPMI+SVD vectors.- No island >50 nodes; median size 15; communities semantically coherent. Examples: island 27 identity, 29 CV/frontend, 38 FTS5/typo.
scripts/experimentos/expD_sinonimia_comunidades.pywas the old experiment.- With oracle island selection + intra-island cosine, 9/13 difficult synonymy cases were rescued. The actual bottleneck was projecting the query into the correct island.
- Earlier softmax top-3 community weighting failed and was abandoned.
- Open issue from the old work: “playa → piscina/mar/fotos” / “descansé → dormí/paz” pure meaning propagation without lexical overlap had not been validated.
- The uploaded file reiterates that the prior system used one weak PPMI projection and identified “projection to correct island” as the key bottleneck.
Fallback experiment B0/B1/B2
docs/informe_fase6_osp_aureon.md(content was in the uploaded markdown):
- B0 FTS5: R@1 1/50, R@5 2/50.
- B1 FTS5 + CSR: same as B0 when CSR abstains.
- B2 CSR→FTS fallback: same as B0.
- CSR isolated hard gate: 0/50 and acts as blocker when no FCC.
- Correct diagnosis: CSR should not hard-block; fallback preserves lexical floor.
- OSP should not be pursued as a giant universal parser yet. Uploaded doc lines 41-46 define the proposed parser benchmark; lines 302-338 discuss multichannel island projection.
expG multichannel island access
- Script:
scripts/experimentos/expG_llave_acceso_multicanal_islas.py - Results on 61 synonymy cases:
- A PPMI 1-vector: Island R@1 25/61=41.0%, R@5 41/61=67.2%, global R@5 20/61=32.8%, MRR .2218
- B PPMI burst 5 views: R@1 42.6%, R@5 68.9%, global R@5 34.4%, MRR .2177
- C 13-D cognitive dimensions: R@1 23.0%, R@5 47.5%, global R@5 14.8%, MRR .0771
- D HDC 2048-bit bundling: R@1 31.1%, R@5 59.0%, global R@5 24.6%, MRR .1268
- E all channels: R@1 47.5%, R@5 72.1%, global R@5 36.1%, MRR .2391
- Initial beam follow-up reported Top-1/3/5 islands and global retrieval improvements up to 45.9% R@5 at Top-5/7 beam depending implementation. In the later expH report, beam numbers differ slightly and must be treated as implementation/context-specific until rechecked.
- Do NOT claim E is best by default; expH showed it is not.
expH ablation 15 channel combinations
- Script:
scripts/experimentos/expH_ablacion_15_canales_concordancia.py - Major result:
A+C(PPMI + 13-D): Island R@1 31/61 = 50.8%, R@5 45/61=73.8%, global R@5 24/61=39.3%, MRR .2596.A+D(PPMI + HDC): Island R@1 30/61=49.2%, Island R@5 48/61=78.7%, global R@5 23/61=37.7%, MRR .2432.- All four
A+B+C+D: R@1 49.2%, R@5 75.4%, global R@5 37.7%, MRR .2432. A+Bshows little gain; B is largely redundant with A.- C and D appear complementary to A.
- C alone and D alone are weak.
- Beam in expH:
- Top-1 island: Global R@5 36.1%
- Top-2: 39.3%
- Top-3: 42.6%
- Top-5: 44.3%
- Top-7: 45.9%, MRR .3164
- Conclusion at this point:
- Best exact island key candidate: A+C
- Best island coverage candidate: A+D
- Do not carry all-four E into production.
- Next proposed experiment: per-case compare A+C vs A+D, determine whether they rescue complementary cases; compute union/intersection and concordance.
- Potential adaptive architecture:
```text
QUERY
┌──────┴──────┐
A+C A+D
precision coverage
│ │
└──────┬──────┘
▼
concordance
┌──────┼──────┐
same nearby conflict
│ │ │
Top-1 Beam fallback
```
- User asked “¿cuál será la llave perfecta para las islas y cómo fabricamos esto para superar el abismo léxico?” Current answer: A+C is the strongest exact-key candidate, A+D is strongest coverage, but neither is close to perfect yet; likely best next architecture is a concordance/union of A+C and A+D with adaptive beam and FTS fallback, not all-four E.
- Need test 61 old cases as regression and separate new validation/test sets to avoid overfitting.
Sandbox Limitations
- No external web research was needed for this coding audit; local repo/artifacts were sufficient.
- Python internet access unavailable in private tools; container can execute local commands.
- Past SQLite issue: benchmark snapshot hash mutates through
log_busquedas; use read-onlyfile:...?...mode=roor redirect logs to memory. - No known port/SSL/proxy issue relevant to current thread.
- Tools available: container, Python, Files. The user’s uploaded big-paste markdown is auto-mounted and already read; exact content is also available through
turn17file0. - Do not invent sandbox paths from file display names; only use verified mounted paths.
Discarded Approaches
- Dense/neural embeddings as the solution: explicitly rejected by user.
- Treating B3/QCR as semantic generalization: rejected; it is a gate/fallback.
- RCIL v0.1 prelexical claim: refuted by zero-lexical-cue tests.
- Generic FCC/default attractor in RCIL v0.2: caused huge collisions; removed.
- Manual rules for each OOF family: explicitly rejected because they would only convert unknown families into known families and not solve generalization.
- Phase 6 “Open Structural Parsing” as a large universal-parser project: deprioritized after user complained about token burn and lack of direct system improvement.
- Hard CSR gate in OOF: caused 0%; B2 FTS fallback restores B0 floor.
- PPMI burst B alone: largely redundant with PPMI A.
- All-channel E (
A+B+C+D) as default production key: inferior to simpler A+C / A+D in expH. - Softmax top-3 island community weighting: failed in earlier experiment and discarded.
- Claim that 9/13 oracle-island rescues proves universal semantic island projection: rejected.
- Claim that abstention on OOF adversarial cases equals semantic robustness: rejected; much was
NO_PROPOSITION_RECOGNIZED.
Goal
- Convert the already-emergent PPMI island structure into a real, measurable improvement of MemoryBioRAG’s lexical-gap retrieval, without adding a giant manual parser or dense neural embeddings.
Objective
- Determine whether the island projection bottleneck can be significantly improved using complementary signals already present in BioRAG, then integrate only a validated, lightweight mechanism into production.
- The immediate scientific question is whether A+C and A+D are complementary enough that an adaptive concordance/beam mechanism substantially beats either alone on truly new queries.
Important Details
- Critical distinction: the 54% Gold re-entry result is strong evidence for compositional structural retrieval within known families, not universal lexical-gap solution.
- OOF 0% exposed the closed extraction bottleneck, but current island work offers a different path because the topology is emergent rather than manually enumerating all concepts.
- Current practical hypothesis:
A+C= PPMI + 13-D, stronger Top-1 island precision.A+D= PPMI + HDC, stronger Top-5 island coverage.- Use agreement/concordance when both point to same island; otherwise use a union/beam of their top islands.
- Fall back to FTS5/PPMI global if structural confidence is weak.
- Need to distinguish “island identification” from “actual global retrieval.” Better island R@5 does not guarantee global R@5, because candidate ranking inside beam can differ.
- The beam experiment should be rechecked for exact channel combination used. The expH report’s beam numbers are tied to the “combination optimal” context and may not correspond to A+C vs A+D separately.
- Before production integration, compare per-case A+C and A+D and then test an adaptive union on new held-out cases. Use old 61 cases as regression only.
- Do not add
Scope(¬)or special adversarial fixes yet. Avoid overfitting. - User wants direct benefit. A successful next step should have a simple acceptance criterion, e.g. materially improving blind validation R@5 without degrading baseline/FP/latency.
Constraints & Preferences
- No dense embeddings/neural model as a solution.
- Prefer existing PPMI+SVD, islands, HDC, 13-D, graph/spreading activation, Concept Hubs.
- No production changes before external/held-out validation.
- No tuning on the same 61 legacy cases used for discovery.
- Keep token expenditure focused on high-value experiments.
- Preserve SHA-256 and git commit traceability.
- Report failure cases as well as rescues.
- Do not call something “perfect” or “solved” without evidence.
- Finished agent messages should use a writing block with
variant="chat_message".
Progress
Done
- Audited canonical v30.2 and B3/QCR.
- Audited RCIL v0.1–v0.6 and structural retrieval experiments.
- Conducted Gold Re-entry Retrieval; 27/50 R@5 with global ranking and 27/27 rank-causal rescues.
- Conducted Gold-blind invariance audit 50/50.
- Conducted strict lexical overlap audit and FTS vs CSR ablation.
- Built/froze OOF 100-case benchmark; showed 0% CSR R@5 and closed parser limitation.
- Measured B0/B1/B2 fallback; showed CSR isolated hard gate is a blocker but fallback preserves floor.
- Revisited old “islands” discovery: 105 emergent communities from mutual kNN + LPA over PPMI+SVD; 9/13 oracle-island intra-island rescues.
- Ran expG multichannel projection:
- E all channels: 47.5% island R@1, 72.1% island R@5, global R@5 36.1%.
- Ran expH 15-channel ablation:
- A+C best Island R@1 50.8%.
- A+D best Island R@5 78.7%.
- E not best; B largely redundant.
- Latest recommendation: per-case A+C vs A+D concordance/union experiment, then test on new blind cases; do not integrate yet.
In Progress
- The next planned experiment is a per-case A+C vs A+D complementarity analysis and an adaptive union/beam key for islands.
- Need to validate whether channels rescue different cases and whether an adaptive
A+C ∪ A+Dstrategy beats the individual branches on new blind data. - Potential integration should wait for blind validation.
Active
scripts/experimentos/expD_sinonimia_comunidades.py: prior island experiment, relevant for methodology and baseline.scripts/experimentos/expG_llave_acceso_multicanal_islas.py: current multichannel island projection prototype.scripts/experimentos/expH_ablacion_15_canales_concordancia.py: 15-combination ablation; next relevant source to inspect if refining combination logic.scripts/experimentos/expA_labels.json: island/community assignments.scripts/casos_qa_baseline_v1.jsonl: source of 61 synonymy cases.- Snapshot:
snapshots/qa_escape_qcr_20260811.db. - No half-implemented production function approved yet for island-key integration.
Blocked
- No hard blocker. Production integration is intentionally blocked pending blind validation.
- “Universal lexical-gap solution” remains unproven.
- Need exact verification of beam implementation and channel-specific beam before concluding optimal beam size.
Key Decisions
- Stop spending cycles on universal symbolic parser OSP for now; focus on island projection because it has existing empirical evidence and could directly improve retrieval.
- Treat
A+Cas the strongest precision branch andA+Das the strongest coverage branch. - Do not use all-four E by default; more channels are not automatically better.
- Next architecture candidate is adaptive concordance + beam + fallback, not simple score summation.
- Old 61 synonymy cases are regression/discovery only; new blind set required for validation.
- No
core/changes until the adaptive island key passes new held-out validation.
Git State
- Branch: only publicly referenced branch is
cuantificarelaporterealdeConceptHubyWordNet; fullgit branch -aoutput is not present in this context. - Remote URL:
https://github.com/dennysjmarquez/MemoryBioRAG.gitis implied by public repo context; verify before issuing push/pull commands. - Last relevant frozen commit:
1e95b8d25b0827012017a2e63f75e963e84acc38; commit message not captured. - Earlier canonical v30.2 commit/tag:
b957a633acbe313b5caedf6f089aa597c0b37f02. - No merge conflicts discussed.
- No push/pull status verified in latest context.
- User expects no production modification until validation.
- Exact git verification commands:
git branch -a
git remote -v
git status --short --branch
git log -n 5 --oneline --decorate
Plan Files / References
docs/fase5_gold_reentry_retrieval.json: 50 Gold re-entry results; 27/50 R@5; rank-causal ablation.docs/fase5_out_of_family_dataset_frozen.json: 100-case frozen OOF dataset; SHA19c5632bbbcb29df3793c1bcff9fd090e1d37e8cb9f2f63ec6a5955454bd8557.docs/fase5_out_of_family_benchmark_results.json: OOF results; SHA01045f2d55fb5df0a0c3232b3049624ea02802fc9ee07922a483ba482591136c.docs/informe_fase6_osp_aureon.mdcontent appears inturn17file0, especially B0/B1/B2 lines 15-22 and OSP lines 117-137.docs/expG_llave_acceso_multicanal_results.json: expG results.docs/expH_ablacion_15_canales_results.json: expH results.scripts/experimentos/expD_sinonimia_comunidades.py: original island pipeline.scripts/experimentos/expG_llave_acceso_multicanal_islas.py: multichannel island projection.scripts/experimentos/expH_ablacion_15_canales_concordancia.py: 15-channel ablation.scripts/experimentos/expA_labels.json: island labels.scripts/casos_qa_baseline_v1.jsonl: 61 synonymy cases.- Uploaded context file:
/mnt/data/Se ha pegado el markdown(1).md; referenceturn17file0; it contains the prior reports and the user’s current reasoning. Relevant lines: 266-279 for islands; 288-338 for multichannel proposal.
Data Structures
- Exact canonical B3 variables/functions above.
- Gold re-entry structure:
reentry_caseslist.- Per case fields observed:
id,gold_target,withheld_A_B,real_retrieval_rank,real_retrieval_score,is_top5,is_top1,query. - Causal audit file fields:
id,gold,A.rank,A.score,B.rank,B.score,A_plus_B.rank,A_plus_B.score,causal_by_rank.
- OOF dataset/result structures:
held_out_details,held_out_50,reentry_cases,summary,metrics_summary,family_breakdown,gold_breakdown,zero_strict_audit.
- expA labels:
expA_labels.jsoncontainsconceptos,knn_lpa.- Prior inspection showed
len(conceptos)corresponds to node labels andlen(set(knn_lpa))gives community count = 105.
- expG inputs/outputs:
cargar_datos_base(DB_PATH, LABELS_PATH)proyectar_canal_A_ppmi(q, data)proyectar_canal_B_ppmi_rafaga(q, data)proyectar_canal_C_dimensiones(q, data)proyectar_canal_D_hdc(q, data)proyectar_canal_E_multicanal(sA, sB, sC, sD)
- Island ranking in one follow-up used:
sorted_islands = [data['sorted_coms'][i] for i in np.argsort(-sE)]- candidate nodes are gathered from
data['com_por_concepto'] - query vector via
data['idx_biorag'].vector_query(_tokenizar(q)) - node scores via dot product with
data['ppmi_map'][node]
- expH combinations:
- A = PPMI 1 vector
- B = PPMI burst 5 views
- C = 13-D dimensions
- D = HDC
- 15 nonempty combinations of four channels tested.
- No localStorage/UI state, CSS selectors, frontend hooks, or browser UI architecture are relevant to this repository thread.
Code Architecture
- Memory retrieval is hybrid classical/symbolic: FTS5/BM25, QCR/B3, symbolic fallback, WordNet, domain dictionaries, PPMI/SVD, Concept Hubs, graph/spreading activation, hybrid scoring, 13 axes, predicates/synapses.
- Island construction: PPMI+SVD vectors → mutual kNN (k=15) → Label Propagation → 105 emergent communities.
- Current island-key experimental architecture:
- PPMI projection (A)
- burst PPMI (B)
- 13-D cognitive signature (C)
- HDC/SDM hypervector (D)
- combined E
- Recommended next architecture:
- A+C precision branch
- A+D coverage branch
- concordance/union
- adaptive beam
- FTS fallback
- No production wrapper/hook exists yet.
- No CSS or JS fixes in this codebase are relevant.
Bug Fixes Log
| Bug | Causa | Fix | Archivo:Línea |
|---|---|---|---|
CSR hard-gated OOF retrieval to 0% when NO_PROPOSITION_RECOGNIZED |
Isolated CSR returned [] instead of delegating |
B2 CSR→FTS fallback restored B0 floor (R@5 4%) | Experimental Fase 6 prototype; exact lines not captured |
| Prior M1 FP criterion was defective | M1 score max 2.0 while FP condition used >2.0, guaranteeing 0 FP |
Audit methodology corrected; do not reuse old FP metric | scripts/evaluar_qa.py / M1 experiment |
| Gold re-entry report overclaimed “new candidate generation” | Gold already existed in Phase B | Reclassified as Structural Query Generation & Compositional Structural Retrieval | Fase 5 docs |
exclude_gold_id could be misinterpreted as Gold-conditioned parser |
Need proof | 50/50 output hash invariance across Gold IDs/empty input | Fase 5 invariance audit |
| OOF “excellent robustness” overclaimed abstention | 48/50 were mostly NO_PROPOSITION_RECOGNIZED |
Reclassified as abstention due to inability to interpret | Fase 5/6 reports |
Build / Run / Verify
- No formal build system commands captured.
- Benchmark canonical command:
BIORAG_QA_GATE=0 BIORAG_PATH=snapshots/qa_escape_qcr_20260811.db \
BIORAG_QA_METRICS=scripts/qa_metrics_v30_2_final.json \
python3 scripts/evaluar_qa.py
- Experiment runs:
python3 scripts/experimentos/expD_sinonimia_comunidades.py
python3 scripts/experimentos/expG_llave_acceso_multicanal_islas.py
python3 scripts/experimentos/expH_ablacion_15_canales_concordancia.py
- Inspect repo state:
git branch -a
git remote -v
git status --short --branch
git log -n 5 --oneline --decorate
- For snapshot safety prefer read-only SQLite connections.
Next Steps
- Run a per-case A+C vs A+D complementarity audit on the 61 legacy synonymy cases. Output
A+Cisland rank,A+Disland rank, whether each is correct at Top-1/Top-5, whether they agree, union success, intersection success. - Recheck/clarify which channel combination produced the expH beam numbers (especially 45.9% global R@5 at Top-7).
- Build a small adaptive-island prototype in
scripts/experimentos/only:
- If A+C and A+D agree → high-confidence Top-1/Top-2.
- If they disagree but one is near → beam over union/Top-N.
- If both low-confidence → FTS5/PPMI global fallback.
- Validate on a new blind development set (about 30) without tuning on the 61 legacy cases; then a separately frozen final blind set.
- Measure:
- Island R@1/R@5
- Global R@1/R@5
- MRR
- FP/adversarial
- latency
- candidate pool size
- Only if blind validation improves substantially and reproducibly, integrate a lightweight version into
core/. Otherwise close this line.
Critical Context
- The user has already expressed concern about “too many experiments for no visible system improvement”; next steps must be tightly targeted and have an explicit go/no-go criterion.
- Current evidence does not support “abismo léxico solved”; it supports a promising topological retrieval mechanism.
- The most actionable current evidence is:
- islands are emergent and coherent;
- oracle island selection previously rescued 9/13 difficult cases;
- A+C and A+D are currently the strongest island projection variants;
- their combination may be more useful through concordance/union than raw all-channel summation.
- Must avoid overfitting: do not optimize new weights on the 61 cases and then report them as test.
- Need verify exact implementation semantics of HDC/13-D projection before production.
- Important distinction:
A+C“best R@1” vsA+D“best R@5” refers to island selection, not necessarily final global retrieval. - Open scientific question: Can adaptive island-key + intra-island ranking yield a reproducible improvement on unseen queries without embeddings?
Relevant Files
core/memory_store.py: production retrieval/gating; do not modify until validated.core/fallback_simbolico.py: symbolic tokenizer/fallback.scripts/evaluar_qa.py: canonical evaluator.scripts/casos_qa_baseline_v1.jsonl: baseline query cases, including 61sinonimo.scripts/experimentos/expA_labels.json: 105 island labels.scripts/experimentos/expD_sinonimia_comunidades.py: original island experiment.scripts/experimentos/expG_llave_acceso_multicanal_islas.py: multichannel island projection.scripts/experimentos/expH_ablacion_15_canales_concordancia.py: 15-combination ablation.docs/expG_llave_acceso_multicanal_results.json: expG output.docs/expH_ablacion_15_canales_results.json: expH output.docs/fase5_gold_reentry_retrieval.json: Gold re-entry results.docs/fase5_out_of_family_dataset_frozen.json: frozen OOF dataset.docs/fase5_out_of_family_benchmark_results.json: OOF results.docs/informe_fase6_osp_aureon.md: Fase 6 diagnostic report./mnt/data/Se ha pegado el markdown(1).md: uploaded conversation/report context; referenceturn17file0.
Next Agent Instructions
Ready-to-paste instructions:
Estamos continuando la auditoría/diseño de MemoryBioRAG. NO empieces otra línea teórica. El objetivo ahora es una mejora real y acotada del retrieval usando las islas emergentes PPMI+SVD.
Primero lee:
1. scripts/experimentos/expD_sinonimia_comunidades.py
2. scripts/experimentos/expG_llave_acceso_multicanal_islas.py
3. scripts/experimentos/expH_ablacion_15_canales_concordancia.py
4. docs/expG_llave_acceso_multicanal_results.json
5. docs/expH_ablacion_15_canales_results.json
6. scripts/experimentos/expA_labels.json
7. scripts/casos_qa_baseline_v1.jsonl
Git primero:
git branch -a
git remote -v
git status --short --branch
git log -n 5 --oneline --decorate
Contexto clave:
- 105 islas emergentes: mutual kNN k=15 + LPA sobre PPMI+SVD.
- Oracle island selection rescató 9/13 en el experimento antiguo.
- expG:
A PPMI = Island R@1 41.0%, R@5 67.2%
E all-channel = 47.5% / 72.1%
- expH:
A+C = 50.8% Island R@1, 73.8% R@5, Global R@5 39.3%
A+D = 49.2% Island R@1, 78.7% R@5, Global R@5 37.7%
E = 49.2% / 75.4%; por tanto E no es mejor.
- A+B es casi redundante; C y D son señales complementarias.
- OOF parser test dio 0% CSR R@5 y mostró que el parser cerrado es el cuello de botella. No volver a crear reglas manuales por familia.
- No tocar core/ todavía.
Próximo experimento obligatorio:
1. Crear una auditoría por caso A+C vs A+D en los 61 casos.
2. Para cada caso: rank de isla A+C, rank de isla A+D, Top1/Top5 para cada uno, concordancia, unión, intersección.
3. Calcular Union R@1/R@5 y concordance.
4. Reconfirmar exactamente qué combinación generó el beam Top-7 del informe expH.
5. Diseñar un prototipo adaptive-island-key:
- acuerdo A+C/A+D → alta confianza
- desacuerdo → beam por unión
- baja confianza → fallback FTS5/PPMI
6. NO ajustar pesos sobre los 61.
7. Después probar en un nuevo conjunto ciego separado.
8. Solo integrar en core/ si la validación ciega mejora de forma reproducible.
No afirmes “abismo léxico resuelto”. El criterio de éxito ahora es una mejora medible de retrieval real, no otra colección de reportes.
Qué demuestra este ejemplo
Este resultado muestra que la herramienta no produce un resumen genérico. Conserva el objetivo del proyecto, el estado del repositorio, el contexto del usuario, las métricas experimentales, las hipótesis confirmadas o rechazadas, los enfoques descartados, las restricciones, los archivos relevantes, los comandos de verificación y las instrucciones exactas para el siguiente agente.
El system prompt transforma una conversación extensa en una memoria técnica transferible y accionable.
