memory-compaction
Skill8 starsChanged 3 months agoMITView on GitHub
Operating procedure for keeping a long-running agent coherent using the OpenAI Agents SDK memory and compaction primitives: three ways to trigger compaction (automatic, threshold-based, forced checkpoint), exact rules for what working state to preserve through a compaction, and what belongs in cross-run memory versus the reviewed output artifact. Trigger when building or operating an agent whose session spans many turns or evidence batches and risks context overflow, when deciding what to persist across sessions, or when wiring Compaction()/Memory() capabilities into a SandboxAgent.
1 other project uses a version of this.
Adopted by
Most recently taken up by
- makushingu/harness-maxxingtheir own version, first seen Nov 8, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 1
- makushingu/harness-maxxing★ 161same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository21 other files it gives its agents.
- agent-design-fundamentalsSkill
- agent-evalsSkill
- agent-failure-preflightSkill
- agentic-coding-disciplineSkill
- agent-improvement-loopSkill
- agent-sandboxingSkill
- coding-agent-securitySkill
- context-compressionSkill
- context-engineeringSkill
- gpt-56-promptingSkill
- long-running-harnessSkill
- mcp-2026-migrationSkill
- mcp-code-executionSkill
- monorepo-agentsSkill
- planner-evaluator-harnessSkill
- prompt-cache-optimizationSkill
- prompt-engineering-canonSkill
- skill-authoringSkill
- spec-driven-devSkill
- tool-designSkill
- zero-trust-agentsSkill
The file
We split this skill into the rules it gives an agent
3 rules. About 0 are common, 2 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 17
Use this skill when:
- Distinctive: line 24
Do NOT use this pattern to:
- Very specific: line 83
Pasting large source content into prompts: instead of materializing it in the workspace via the Manifest.
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Memory & Compaction for Long-Running Agents
This skill gives you the OpenAI Agents SDK pattern for keeping a multi-turn, multi-batch agent coherent: compaction sustains the current session when context grows, memory carries reusable workflow lessons into future sessions, and a generated, human-reviewed artifact (a memo with citations) remains the only system of record. The three are deliberately separated — no single one of them (not conversation history, not memory, not agent reasoning) replaces human review of the cited output. The reference implementation is an evidence-review agent for compliance investigations, but the pattern applies wherever knowledge workers review evolving context and produce auditable outputs: support escalations under policy updates, security incident summaries, finance exception reconciliation, legal/procurement contract review, M&A diligence.
When to use
Use this skill when:
- A single agent session must survive many turns or sequential evidence/document batches and will hit context limits mid-task.
- You are wiring a
SandboxAgentwithFilesystem()andShell()capabilities and need to addCompaction()and/orMemory(). - You must decide, at a phase boundary, what to keep in working context, what to promote to cross-run memory, and what to write into the output artifact.
- Repeated runs of the same kind of task should get better over time without replaying every prior interaction.
Do NOT use this pattern to:
- Store task conclusions or case facts in memory — those belong in the reviewed output artifact with citations.
- Replace a reviewed deliverable with compacted summaries or memory files.
- Manage short sessions that fit comfortably in one context window — the machinery adds no value there.
Rules
- Separate the three primitives by purpose. Compaction summarizes active conversation and working state so one long-running session can continue. Memory stores patterns, preferences, and process lessons so future sessions improve. The generated memo is the definitive, human-reviewed artifact. Neither compaction nor memory ever stores investigation conclusions.
- Stage inputs in the workspace, not the prompt. Describe the fresh-session workspace with a
Manifest(fields:root— defaults to/workspace;entries;environment;users/groups;extra_path_grants;remote_mount_command_allowlist). Keep entry paths workspace-relative for portability across Unix-local, Docker, and hosted providers. Put long task instructions in workspace files (README.md,task.md); keep agent instructions focused on boundaries. Use smallFile(...)/Dir(...)entries for tutorials;LocalDir,GitRepo, or storage mounts for production data. Keep mount scopes narrow; inject secrets as runtime configuration, never as prompt text or committed manifests. - Make findings citable. Use stable document IDs and a machine-readable manifest (e.g.,
manifest.csv) so the memo cites traceable sources. The source's baseline instruction requires every finding to cite document IDs frommanifest.csv, and requires incomplete evidence to be logged as an open question rather than guessed at. - Pick the compaction trigger by how much control you need. Three ways: (a) automatic — attach
Compaction()and the SDK compacts when context pressure requires it; often sufficient for production; (b) threshold-based —Compaction(policy=StaticCompactionPolicy(threshold=...))for predictable context-size behavior (the demo uses8_000); (c) forced checkpoint —OpenAIResponsesCompactionSession.run_compaction({"force": True})at an application-defined phase boundary, such as after a major review phase and before the next evidence batch. - Tell the agent what compaction must preserve. Amend instructions explicitly. From the source: "When context is compacted, preserve the current batch, cited facts, open questions, artifact paths, and unresolved reviewer concerns." Summarized impressions alone are not enough working state.
- For forced checkpoints, wrap a persistent session. Construct
OpenAIResponsesCompactionSession(session_id=..., underlying_session=SQLiteSession("evidence_review_session.sqlite"), model=COMPACTION_MODEL, compaction_mode="input"), then callawait session.run_compaction({"force": True, "compaction_mode": "input"}). Verify effectiveness by comparing session item counts fromsession.get_items()before and after the call. The demo uses a cheaper dedicated compaction model (COMPACTION_MODEL = "gpt-5.4-mini"vsMODEL = "gpt-5.5"for the agent) andmax_turns = 12. - Restrict memory to workflow lessons. Good memory candidates: use the manifest first when reviewing file-based evidence workspaces; preserve uncertainty in the memo instead of guessing; keep earlier assumptions visible when later evidence narrows them. Bad candidates (they belong in the memo): specific findings or violations, evidence-specific facts or citations, case conclusions about any entity's conduct.
- Steer memory generation with
MemoryGenerateConfig.extra_prompt. ConfigureMemory(generate=MemoryGenerateConfig(extra_prompt=...))and state explicitly what NOT to store — the source's prompt forbids storing case-specific compliance findings, document facts, evidence citations, or memo conclusions, directing them to the memo file instead. The SDK writesmemories/MEMORY.mdandmemories/memory_summary.mdvia a sandbox pre-stop hook before session termination; letMemory()manage its own artifacts (memories/,sessions/) and keep generated outputs underoutputs/. - Combine all three in the final agent. Capabilities:
[Filesystem(), Shell(), Compaction(), workflow_memory()], plus instructions that say: use compaction as working context; use SDK memory for reusable workflow lessons across runs; do not treat memory as the system of record for findings — those belong in the cited memo artifact. - Keep superseded assumptions visible. As batches arrive, do not silently delete assumptions that later evidence narrowed or overturned — track the change in working notes and the memo. The memo (e.g.,
outputs/compliance_review_memo.md) contains: executive summary (distinguish control gaps from definitive violations), cited findings table (each finding with its supporting document IDs and status), open questions, recommended next steps for the reviewer. - Under Zero Data Retention, disable tracing. Set
os.environ["OPENAI_AGENTS_DISABLE_TRACING"] = "true"whenDISABLE_TRACINGis on.
Compaction vs memory at a glance
| Aspect | Compaction | Memory |
| Purpose | Continue one long-running session as context grows | Improve future runs with reusable lessons |
| Summarizes | Active conversation and working state | Patterns, preferences, process lessons |
| Store conclusions? | No — working state only; memo is the record | No — workflow lessons, not case facts |
| Useful when | Mid-review, before later batches or follow-up turns | Across repeated reviews of similar workflows |
Checklist
- Workspace staged via
Manifest(workspace-relative paths); long instructions inREADME.md/task.md, not the prompt. - Stable document IDs + machine-readable
manifest.csvso every finding is citable. - Compaction trigger chosen: automatic
Compaction()(default),StaticCompactionPolicy(threshold=...)(tighter control), or forcedrun_compaction({"force": True})at phase boundaries. - Instructions amended: on compaction, preserve current batch, cited facts, open questions, artifact paths, unresolved reviewer concerns.
- Forced-checkpoint path uses
OpenAIResponsesCompactionSessionover aSQLiteSession, withcompaction_mode="input"; item counts compared viaget_items()before and after. - Cheaper dedicated compaction model configured if cost matters (source:
gpt-5.4-miniundergpt-5.5). Memory(generate=MemoryGenerateConfig(extra_prompt=...))steers memory to workflow lessons only; forbidden content named explicitly.- Memory artifacts (
memories/MEMORY.md,memories/memory_summary.md,sessions/) left to the SDK; outputs written underoutputs/. - Final artifact has executive summary, cited findings table, open questions, next steps — and is the only thing handed to reviewers.
- Incomplete evidence recorded as an open question, never guessed.
- Secrets injected as runtime configuration; mount scopes narrow; tracing disabled under ZDR.
Anti-patterns
- Treating memory as unreviewed fact storage. "Do not treat
Memory()as an unreviewed fact database." Memory helps the next agent work better; it must not become a shadow database of conclusions. If a conclusion matters, write it into the reviewed memo with citations. - Compacting away necessary working state. Setting thresholds or forcing checkpoints without ensuring cited facts, open questions, and artifact paths survive leaves only summarized impressions — the next turns can't recover.
- Mixing case-specific and workflow-generic memory. Without an explicit
extra_promptsteer, memory generation absorbs case findings; keep it strictly on process lessons. - Silently deleting narrowed assumptions. Superseded assumptions must stay visible in notes and the memo so reviewers can trace how conclusions evolved.
- Pasting large source content into prompts instead of materializing it in the workspace via the
Manifest. - Letting any component replace human review. Compacted history, memory files, and agent reasoning are all inputs; the cited, human-reviewed memo is the record.
Source
- Building Reliable Agents with Memory and Compaction — https://developers.openai.com/cookbook/examples/agents_sdk/building_reliable_agents_memory_compaction — 2026-05-01
Distilled from the official document(s) above on 2026-08-12. If this skill and the source disagree, trust the source.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

