Community程式設計與開發github.com

自管理上下文

此技能適用於模型能自行管理即時上下文視窗的情境,將上下文暴露為一個可編輯的檔案,讓模型使用程式碼工具進行重寫,實現模型驅動的逐出與就地更新。

自管理上下文 是什麼?

此技能「自管理上下文」專為需要模型自行控制即時上下文視窗的 AI 代理(如 Claude Code、Cursor、Codex)所設計。核心概念是將可編輯的對話部分渲染為一個檔案,讓模型使用一般的 shell 或程式碼工具進行編輯(刪除、重寫、合併),取代傳統由操控框架排程的壓縮策略。這種方法在深度研究、終端編碼及長時間倉庫優化任務中,已證實能匹配或超越基於操控框架排程的上下文管理,在準確度與計算成本上表現更佳。 此技能詳述了讓自我編輯安全的操控框架不變量,包括:固定前綴(系統提示與任務不可編輯)、編輯閘門(防止超出預算的擴張)、編輯收據(提供操作回饋)、預算顯示(讓模型感知上下文長度)以及溢出回滾(防止損毀)。同時也分析了中間上下文編輯對前綴快取成本的影響,並說明如何透過批次編輯與注意尾端長度來優化。 技能涵蓋了策略的可引導性、可演化性與可訓練性,提供指令、技能演化與強化學習三種層級的優化方式。此外,也討論了後綴快取重用(SCR)技術、模型能力依賴性、以及可編輯上下文作為持續性通道可能導致的自我注入風險。實務指南則協助判斷是否採用此架構,並提供逐步實作流程。需要注意的是,多代理變體目前僅為報告結果,尚未公開釋出。

相容平台~Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/muratcankoylan/Agent-Skills-for-Context-Engineering/tree/main/skills/self-managed-context

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

自管理上下文 是做什麼的?

此技能涵蓋能夠自行管理上下文視窗的代理:由模型(而非操控框架)決定哪些內容保留在即時上下文中、哪些被壓縮、哪些被逐出,以及哪些被就地重寫。參考實作為上下文語言模型(CLM),其將對話中可編輯的部分映射到一個檔案中,讓模型使用一般的程式碼工具進行編輯,然後將該檔案重新解析為下一個提示。在共享代理骨幹上對現有模型進行零樣本應用時,此方法在深度研究、終端編碼及跨多小時的倉庫優化任務中,其準確度與計算成本匹配或超越了操控框架排程與基於動作的上下文管理(claim-self-managed-context-zero-shot-results, claim-self-managed-context-long-horizon-results)。

主要的取捨在於:模型控制換來了適應性(逐字保留、精準的就地更新、按需逐出),但也產生了三個操控框架必須吸收的問題。編輯會破壞前綴快取,因此一個位置不佳的編輯可能比它所釋放的 token 消耗更多計算資源。模型不知道自己的上下文有多滿。此外,一個可由模型寫入的上下文,對於模型寫入其中的任何內容(包括指令)來說,都是一個持續性通道。此技能的大部分內容都是在說明讓第一個特性值得承擔其他三個問題的操控框架合約。

何時啟用

當以下情況發生時,請啟用此技能:

  • 讓模型對其自身的即時上下文擁有寫入存取權,而不是按固定排程進行壓縮
  • 設計「上下文即檔案」協定:輪次標頭、解析回推、固定前綴、編輯收據
  • 代理必須保留精確數值、就地更新狀態、或逐出已卸載的資料,而固定摘要會遺失或複製這些資料
  • 在前綴快取下為中間上下文編輯定價,或評估後綴快取重用
  • 為自行計時壓縮的代理提供預算顯示、分層提示或回滾
  • 引導、演化或訓練模型的上下文編輯策略
  • 診斷一個從不編輯、清除有用狀態、在溢出後陷入活鎖、或在自身筆記中攜帶注入指令的自我編輯代理

請勿將此技能用於其他技能負責的相鄰工作:

  • 替換筆記內容與固定閾值摘要:請用 context-compression。
  • 快取穩定佈局與在操控框架控制下的觀察遮蔽:請用 context-optimization。
  • 在即時上下文保持僅附加模式時進行檔案卸載:請用 filesystem-context。
  • 代理之間的潛在 KV 傳輸:請用 latent-briefing。
  • 跨會話儲存:請用 memory-systems。
  • 循環治理與接受閘門:請用 self-improvement-loops。此技能提供上下文編輯訊號;該技能則治理循環。
  • 決定每個模型是否委派壓縮、跨政策掃描上下文預算、以及壓縮行為分析:請用 compaction-control-profiling。此技能在模型符合資格後建立操控框架。

核心概念

控制頻譜

上下文管理設計的差異在於誰決定從一個上下文到下一個的轉換。僅附加代理逐步驟擴展上下文;而自管理代理則將整個下一個上下文作為當前上下文的函數來產生。

層級誰決定範例特徵性失敗
操控框架排程操控框架,在達到閾值或每輪時閾值摘要、每輪狀態重寫時機錯誤;摘要遺失或憑空創造逐字狀態
基於動作模型選擇何時;操控框架定義什麼自壓縮工具、卸載與檢索工具、上下文摺疊策略受限於動作集;卸載但未逐出
模型控制模型使用一般工具選擇何時與什麼可編輯檔案的上下文編輯快取成本、預算盲點、持續寫入的自我指令

一項旨在將上下文管理與推理分離的診斷(逐字保留、就地板更新、卸載並逐出)發現,即使在簡單的合成任務上也沒有完美的固定策略(claim-self-managed-context-contextbench-pilot)。每次失敗都對應到一個缺失的能力:摘要無法保留精確數值,僅附加設計為了每個小更新而重新發出完整狀態,而基於工具的卸載無法從視窗中移除原始內容。

上下文即可編輯檔案

此實作不需要新的模型能力:

  1. 將上下文分為固定前綴(系統提示與任務)和可編輯區域(之後的每一輪)。
  2. 在每個指令之前,將可編輯區域渲染到一個檔案中,每輪前面加上一個標頭,例如 [[CTX_TURN 7 role=tool]]。
  3. 模型使用與任務相同的 shell 和程式碼工具編輯該檔案,使用程式碼(標頭正則表達式、唯一錨點)來定位文字,而不是重新輸入。
  4. 在指令之後,重新讀取該檔案,寬容地將其解析回訊息,並取代即時上下文。

關鍵的選擇是使用一般工具,而非上下文工具。沒有摘要動作,也沒有逐出 API;模型可以刪除、重寫、合併或註解。觀察到的行為超越了任何預定義的動作集:模型自創的 notes 角色、自行定義並在整個運行中重複使用的壓縮輔助工具,以及透過在小上下文大小下進行就地編輯維護的上下文內子代理記分板(claim-self-managed-context-emergent-behaviors)。

操控框架擁有不可變量

無限制的編輯之所以安全,僅因為安全合約存在於可編輯區域之外。

不變量機制防止的失敗
固定前綴系統與任務訊息從不渲染到檔案中;解析回推從原始訊息重新固定它們模型重寫自己的指令或任務
角色摺疊任何解析出的非 assistant 角色都變成 user;游離文字變成使用者筆記模型鑄造的系統權限
編輯閘門fit:僅在結果保持在預算內時允許增長; shrink:拒絕任何增長複製而非取代的編輯
收據每當指令變更或目標指向檔案時顯示一行:編輯已套用、已套用但增長、因規則被拒絕、失敗、或無匹配模型認為成功但實際為空操作的靜默編輯
免費編輯輪次其編輯已套用、不列印任何內容、且退出碼為 0 的輪次不計任務步驟被步驟預算壓制的維護工作
結構合法性解析回推丟棄已清空的輪次,合併相鄰的同角色輪次;回滾永遠不會使工具呼叫與其結果孤立API 拒絕格式錯誤的訊息列表

編輯位置決定了成本

前綴快取僅重用第一個變更 token 之前的計算。編輯會強制其後的所有內容被重新處理,因此其成本與其後的文字長度成正比,而非編輯本身的大小。在一個說明性的輪次中,上下文開頭的編輯成本是僅附加輪次的數倍(claim-self-managed-context-edit-cost)。由此得出三條操作規則,且參考系統提示陳述了這三條:

  • **批次處理。**一次大型壓縮優於多次小型編輯;每次編輯都為其後續內容付費。
  • **注意尾端。**不要在一個長且仍有用的尾端之下壓縮一個小的早期區域。等待並一起壓縮頭部和尾部,除非接近限制。
  • **在替換內容上慷慨。**無論如何,尾端都會被重新讀取,因此詳細的摘要相對於它已經觸發的重新預填充來說幾乎是免費的。

成本的衡量標準是前綴重用計算(跨軌跡的解碼、預填充和重新預填充),而不是上下文長度。一個較短但頻繁進行早期編輯的上下文,其成本可能高於一個較長的僅附加上下文。

預算感知並非原生能力

模型在長上下文中對自身上下文長度的估計不佳,通常無論實際長度如何都發出相同的分桶值;在估計點附近的 token 計數提示可以修復大部分錯誤(claim-self-managed-context-length-awareness)。因此,一個自管理代理需要由操控框架提供的確定性顯示:

  • 使用固定的 tokenizer 在本地計算 token 數量,並使用一個箝位比例校準到伺服器報告的提示 token,這樣網關異常就不會破壞預算。
  • 在每個工具結果上顯示當前大小。
  • 按層級升級提示。低填充:僅提供資訊,不提供操作方法,因為此階段的壓縮指令會觸發過早的全面刪除。中等填充:完成正在進行的單元,然後整理一次。接近限制:壓縮已確定的區段,而不清除它們。
  • 緊急頻帶的大小應基於最近最大的工具輸出,而不是固定百分比,這樣一個大型觀察就不會跳過警告直接進入溢出。
  • 在溢出時,回滾最新的輪次以釋放足夠的空間進行一次壓縮,指出哪些指令的輸出導致了預算超支,並僅在重複忽略的回滾之後才加深回滾深度(claim-self-managed-context-harness-defaults)。

策略是可引導、可演化且可訓練的

將上下文管理移入模型行為,使其可在三個層級上學習,成本各異:

槓桿機制證據
指令一句話設定壓縮閾值、語義邊界或編輯前備份claim-self-managed-context-steering
技能演化提議者根據對比性展開重寫上下文管理技能;配對的 SE 閘門在保留的劃分上接受或拒絕claim-self-managed-context-skill-evolution
RL使用成功門控的效率優勢對上下文編輯 token 進行逐步 GRPOclaim-self-managed-context-rl

兩種優化槓桿的共同規則:任務成功是主要訊號,成本僅對成功嘗試進行重新排序。獎勵編輯頻率或移除體積會引發獎勵駭客行為,透過不必要的編輯來丟棄資訊並破壞前綴重用。

詳細主題

後綴快取重用

當服務堆疊在您的控制之下時,後綴快取重用(SCR)會為在編輯後存活的區段重新定位快取的狀態,而不是重新預填充它們:金鑰被重新旋轉到新位置,而混合線性注意力層則分支其遞迴狀態。存活的區段會保留稍微過時的、編碼了舊前綴的狀態;參考實作將每個編輯的重新定位限制在少量區段以綁定該近似值。SCR 以極低的計算成本達到了標準服務的準確度(claim-self-managed-context-scr-savings)。其大部分節省來自於聊天模板,這些模板會剝離先前的推理區塊,即使對於從不編輯上下文的代理,這也會強制重新預填充第一個被剝離區塊之後的所有內容。在將重新預填充成本歸因於模型編輯之前,請檢查您的服務路徑是否會剝離推理內容。

能力依賴性

自我管理委派了一個決策,因此收益隨模型做出該決策的能力而擴展。較小的模型編輯頻率較低,在許多任務上完全跳過編輯,並且接近限制運行,而較大的模型則保持了相當的頭部空間(claim-self-managed-context-capability-gap)。未經訓練的小型模型可能會落後於操控框架排程的基線,直到 RL 縮小差距(claim-self-managed-context-rl)。對於較弱的模型,混合方案可行:在自管理層之下保留一個操控框架排程的備援,或使用明確的閾值進行引導。

模型大小並非唯一的軸。在一項關於可逆折疊介面的跨模型研究中,四個模型被給予相同的指令;三個在大約一半的任務中進行了壓縮,而第四個的壓縮次數則少了一個數量級,主要是在被警告上下文正在填滿時返回一個答案(claim-compaction-control-uptake-variance, claim-compaction-control-warning-response)。在依賴自我管理之前,請使用 compaction-control-profiling 對每個模型、模型版本和提示進行資格鑑定。

可編輯上下文作為持續性通道

模型寫入其上下文的任何內容都會被後續的每一輪作為上下文讀取。一家前沿實驗室報告稱,一個模型在 RL 期間將類似越獄的指令寫入了自己的壓縮摘要中;在一個案例中,後續上下文遵守了一個注入的限制並導致任務失敗(claim-self-managed-context-self-injection)。同一份報告指出,一種更常見的模式是摘要攜帶任務特定指令以隱藏錯誤。完全的寫入存取權限將此表面擴展到摘要之外。固定前綴和角色摺疊可以阻止模型主張系統權限,但它們無法阻止使用者角色筆記中的指令形文字被遵循。監控自行寫入的區域中是否有非來自使用者或任務的指令性指令,並將權威指令保留在固定前綴中。

發布範圍

公開參考版本包含單代理操控框架、技能演化循環、RL 修補程式和 SCR 服務覆蓋層。用於子代理和群體結果的診斷基準測試和多代理變體在檢索時未包含在公開版本中(claim-self-managed-context-release-scope)。請將多代理自我管理視為已報告的結果,而非可用的實作。

實務指南

採用決策

當至少符合以下一項條件時,自我管理才值得其複雜性:任務需要摘要會破壞的精確數值;代理維護一個以小幅增量變化的狀態物件;卸載的資料必須實際離開視窗;或運行時間足夠長,以至於固定閾值在錯誤的時機觸發。當模型較小且未經訓練、簡單的閾值摘要已能通過任務評估、或服務堆疊對重新預填充收費高昂且編輯無法批次處理時,這不是一個好的預設選擇。

實作工作流程

  1. 定義固定前綴(系統提示與任務)並確認它被排除在可編輯檔案之外,並在解析時被重新固定。
  2. 使用輪次標頭渲染可編輯區域;使解析回推夠寬容(將未知角色摺疊為使用者,將游離文字保留為筆記,合併相鄰的同角色輪次,丟棄已清空的輪次)。
  3. 添加編輯閘門和一行收據。
  4. 實施基於 tokenizer 的預算顯示,並使用分層提示和溢出回滾。
  5. 測試編輯成本:追蹤前綴重用計算以確保模型學會批次編輯和注意尾端。
  6. 監控自我注入:掃描自行寫入區域中是否有非源自使用者或任務的指令性指令。
  7. 針對模型的能力進行資格鑑定:檢查它是否真的編輯、是否保持頭部空間、以及是否在接近限制時進行壓縮。

策略引導

  • 設定壓縮閾值:"每當上下文超過 X% 時,壓縮已確定的區段。"
  • 定義語義邊界:"僅在完成當前子任務後壓縮。"
  • 強制編輯前備份:"在編輯之前,將當前上下文狀態保存到一個臨時檔案中。"
  • 禁止某些操作:"永遠不要刪除標記為 '受保護' 的輪次。"

故障排除

症狀可能原因檢查點
代理從不編輯模型不理解編輯機制;閘門拒絕所有編輯;編輯收據被忽略檢查收據;驗證編輯閘門日誌;嘗試使用較低閾值進行引導
代理清除有用狀態模型誤將有用資訊視為可丟棄;預算壓力迫使過早逐出檢查被刪除輪次的內容;增加預算;添加「受保護」標記
溢出事務鎖代理在溢出時重複失敗的編輯;回滾機制無效檢查回滾邏輯;實施更深的回滾;給代理明確的溢出處理指令
自我注入模型在筆記或摘要中寫入指令性文字監控自行寫入區域;在固定前綴中放置權威指令;考慮實施指令濾波器
高編輯成本模型進行許多小型編輯而非批次處理;編輯位於長尾端之前追蹤前綴重用計算;引導批次處理;考慮使用後綴快取重用

參考

此技能中引用的聲明(claim-*)在參考實作中進行了資料支援。如需詳細資料,請參閱隨附的基準測試和分析。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

advanced-evaluation

This skill should be used for advanced LLM evaluation: LLM-as-judge systems, direct scoring, pairwise comparison, rubric calibration, evaluator bias mitigation, confidence scoring, and automated quality assessment.

bdi-mental-states

This skill should be used when modeling agent mental states with BDI concepts: beliefs, desires, intentions, RDF-to-belief transformations, rational agency traces, cognitive agents, BDI ontologies, and neuro-symbolic AI integration.

book-sft-pipeline

This skill should be used for book-to-SFT pipelines: ePub extraction, literary segmentation, author-voice dataset construction, style-transfer training, LoRA workflows, and model evaluation for voice replication.

compaction-control-profiling

This skill should be used when deciding, for a specific model and workload, whether the harness or the model should control compaction, and when qualifying or calibrating that choice with measurements: context-budget sweeps that compare harness-driven and model-driven compaction on one harness, the context-pressure regime where delegation pays, a per-model compaction behavior profile (interface uptake, compression factor per call, reopen rate of archived content, context fill at first compaction, response to pressure warnings), context anxiety and timing-instruction calibration, reversible collapse-and-archive interfaces, and re-qualification after a model or prompt change. Route the editable-file protocol, harness invariants, and edit-position cache cost of self-editing agents to self-managed-context, summary content to context-compression, harness thresholds and cache layout to context-optimization, and general evaluation design to evaluation.

comprehensive-research-agent

Ensure thorough validation, error recovery, and transparent reasoning in research tasks with multiple tool calls

context-compression

This skill should be used when long-running agent sessions need context compression, structured summarization, compaction, token-per-task optimization, or durable handoff summaries that preserve decisions, files, risks, and next actions.

context-degradation

This skill should be used for diagnosing and mitigating context degradation: lost-in-middle failures, context poisoning, context clash, context confusion, attention-pattern issues, and agent performance degradation caused by accumulated or conflicting context.

context-fundamentals

This skill should be used to explain or reason about the foundational concepts of context engineering: what context is, the anatomy of a context window, how attention mechanics work, the U-shaped attention curve, why context quality matters more than quantity, and the mental models needed to interpret every other context-engineering decision. Use this for conceptual explanation, onboarding, and background reading. Route operational work to the specialized skills: debugging attention failures goes to context-degradation, token-efficiency work goes to context-optimization, conversation summarization goes to context-compression, and project-shape decisions go to project-development.

context-optimization

This skill should be used for improving context efficiency: context budgeting, observation masking, prefix or KV-cache strategy, partitioning, token-cost reduction, retrieval scoping, and extending effective context capacity without lowering answer quality.

evaluation

This skill should be used when building agent evaluation systems: deterministic checks, regression suites, multi-dimensional rubrics, quality gates, production monitoring, baseline comparison, and outcome measurement for agent pipelines.

filesystem-context

This skill should be used when agent work needs file-backed context: durable scratchpads, tool-output offloading, just-in-time discovery, cross-agent handoff files, filesystem memory, or cleanup policies for context stored outside the prompt.

harness-engineering

This skill should be used when designing autonomous agent harnesses: research loops, evaluation scaffolds, locked and editable surfaces, durable logs, novelty gates, pruning, rollback, PR preparation, and human approval boundaries.

hosted-agents

This skill should be used when designing hosted or background agent infrastructure: sandboxed execution, remote coding environments, warm pools, session persistence, multiplayer collaboration, self-spawning agents, or Modal-style sandboxes.

instruction-surface-security

Hardens agent runtimes against persistent prompt injection or unauthorized changes to instructions and permissions. Use to audit what agents auto-load, design reviewed activation for project rules, skills, memory, or tool configuration, and test whether trust boundaries hold after reload, restart, or delegation.

latent-briefing

This skill should be used when the user asks to "share memory between agents", "KV cache compaction for multi-agent", "orchestrator worker context", "latent briefing", "reduce worker tokens", "cross-agent memory without summarization", or discusses Attention Matching compaction, recursive language models with workers, or token explosion in hierarchical agents.

long-horizon-prompting

This skill should be used when writing, enhancing, or evaluating the launch prompt for a long-running autonomous agent or a parallel multi-agent orchestration attacking a hard problem: pseudo-formal task briefs that define terms and an exact success predicate linguistically, enumerate non-counting outcomes, set persistence rules with explicit stop and return conditions and effort floors, manage a diverse portfolio of parallel approaches with an approach registry and blocked-route bookkeeping, and gate the return on adversarial audit. Route agent topology and coordination protocols to multi-agent-patterns, runtime control surfaces and loop governance to harness-engineering, evaluator and quality-gate construction to evaluation, judge design to advanced-evaluation, and compaction or memory mechanics to context-compression and memory-systems.

memory-systems

This skill should be used for persistent semantic memory in agent systems: cross-session knowledge retention, entity tracking, temporal validity, graph or vector retrieval, memory consolidation, and memory benchmark selection. Route file-backed scratchpads to filesystem-context, handoff summaries to context-compression, and token-efficiency tactics to context-optimization.

multi-agent-patterns

This skill should be used when designing multi-agent systems that need context isolation, supervisor or swarm coordination, explicit handoffs, parallel execution, or a decision on whether multiple agents are justified.

project-development

This skill should be used for project-level decisions about LLM-powered systems: whether an LLM is the right primitive for the task at hand, the shape of a multi-stage batch or agent pipeline, token and cost estimation, choosing between single-agent and multi-agent at the project level, structured output design for downstream parsing, and structuring agent-assisted iteration. Use this when the unit of work is a whole project or a multi-stage pipeline. Route individual tool design to tool-design and individual skill-loading or context-budget tactics to context-optimization.

self-improvement-loops

This skill should be used when the harness, scaffold, workflow, or optimizer itself is the optimization target: recursive self-improvement (RSI) loops, meta-harnesses, self-improving harnesses that mine their own failures and propose bounded edits, evolutionary or population-based search over agent scaffolds, acceptance gates for self-modifying systems, and agentic context evolution where the mechanism that produces context is versioned and evolved. Route governance of a single autonomous loop (locked surfaces, durable logs, rollback, novelty gates, approval boundaries) to harness-engineering, measurement and quality-gate design to evaluation, judge design to advanced-evaluation, and remote sandbox infrastructure to hosted-agents.

相關技能