- 3.1 Implement agent memory strategies — short-term, long-term and external memory; scoping; expiration, pruning and reset
- 3.2 Persist agent state and manage context drift — durable artifacts, resuming without repetition, detecting and correcting drift
- 3.3 Ensure continuity across tools and environments — sharing state, preventing conflicting and stale context
3.1 Implement agent memory strategies
Short-term, long-term and external memory
An agent should not rely on a single stream of context. Organize what it knows into three tiers, each with a different lifetime and purpose.
flowchart TB
subgraph EXT["External memory — the source of truth"]
direction TB
subgraph LT["Long-term memory — curated, reusable"]
direction TB
ST["Short-term memory<br/>the current session's context window"]
end
end | Tier | What it holds | Lifetime | GitHub examples |
|---|---|---|---|
| Short-term | The current task's instructions, recent feedback, tool results, next steps | One session — lost, or compacted, when it ends | The context window of a cloud agent or CLI session |
| Long-term | Curated, reusable knowledge: conventions, key decisions, repeatable procedures | Across tasks and sessions | Custom instructions, AGENTS.md, skills, custom agent prompts, Copilot Memory |
| External | The durable record: requirements, plans, decisions, results | As long as the artifact exists | Issues, PR descriptions and comments, ADRs and docs, workflow runs and artifacts |
External memory is the source of truth
When short-term context and an issue disagree, the issue wins. Anything that must survive the session — acceptance criteria, an approved plan, a decision — belongs in an artifact the agent (and the next person) can re-read, not in chat history.
Choose where each kind of information lives
| Information | Store it in | Why |
|---|---|---|
| Requirements and acceptance criteria | The issue | The agent can revisit the goal and validate against it |
| Plan and decisions | PR description or an ADR in docs/ | Keeps work consistent across sessions without re-interpretation |
| Conventions and validation rules | Repository custom instructions | Applied automatically to every task |
| Rules for part of the codebase | Path-specific instructions with applyTo, or a nested AGENTS.md | Only loaded where relevant |
| Repeatable procedures | Agent skills (SKILL.md plus scripts) | Loaded on demand, not on every request |
| Execution results | Workflow logs and uploaded artifacts | Durable, linkable evidence |
| Facts the agent works out for itself | Copilot Memory | Learned over time; validated before use |
| Credentials | Agents secrets — never memory, instructions or prompts | Secrets are masked and scoped; memory is not a vault |
Copilot Memory
Copilot Memory (public preview) lets Copilot build its own understanding of a repository and of your preferences, instead of making you restate them or maintain ever-growing instruction files. It is used by Copilot cloud agent, Copilot code review, Copilot CLI and agentic autofix, and a fact learned by one can be used by another.
| Repository-level facts | User-level preferences | |
|---|---|---|
| Content | Coding conventions, architecture decisions, build commands, project rules | How a specific user likes to work with Copilot |
| Created by | Activity of users with write access who have Memory enabled | That user's own interactions |
| Available to | Everyone with Memory access to that repository — and only in that repository | Only that user, across repositories |
| Stored with | Citations to the supporting code, checked against the current branch before use | Citations that may include the user's own words |
| Managed by | Repository owners review and delete them (Settings → Copilot → Memory) | The user; on Business/Enterprise, admins can export (JSONL) or delete them |
| Used by code review? | Yes | No — code review applies repository facts only |
- Retention: any fact or preference that goes unused is deleted automatically after 28 days; the timer can reset whenever Copilot successfully validates and uses the entry.
- Validation: only validated facts are used — a fact captured from a PR that was closed unmerged has no effect unless the current code still supports it.
- Enablement: per user, not per repository. On by default for individual plans; off by default for organization and enterprise plans until an administrator enables the policy, after which users are opted in and can opt out. With licences from several organizations, the most restrictive setting wins.
- Audit: exports, deletions and user opt-outs appear in the organization or enterprise audit log.
Copilot Memory versus custom instructions
Custom instructions are written by people, versioned in the repository and reviewed through pull requests. Copilot Memory is learned by Copilot, stored by GitHub, validated against the code and expires when unused. Put anything that must be authoritative or reviewed in instructions; let Memory capture the incidental knowledge.
Scope memory to task-relevant information
Memory should contain only what affects the outcome: requirements and constraints, decisions that shape the implementation, and how to validate it. Temporary intermediate steps and duplicated context should not be kept — they crowd the context window and invite outdated information back in.
- Use path-specific instructions so payment rules load only for payment code, and
excludeAgentto keep a file away from code review or cloud agent. - Place nested
AGENTS.mdfiles next to the code they describe — the nearest one in the directory tree takes precedence. - Prefer skills for long procedures: they load only when relevant, instead of occupying every request.
- In Copilot CLI, very large tool outputs (over 20 KiB by default) are saved to a file and only a preview enters the context.
---
applyTo: "src/payments/**"
excludeAgent: "code-review"
---
- Money is stored as integer cents; never use floating point.
- Every change here needs a unit test in tests/payments/.
- Decision record: docs/adr/0007-idempotency-keys.md is the source of truth for retries. Define memory expiration, pruning and reset rules
| Rule | Mechanism |
|---|---|
| Expiration | Copilot Memory drops unused entries after 28 days. Actions logs and artifacts are retained 90 days by default, configurable per repository, organization or enterprise (1–90 days for public repositories, up to 400 for private); retention-days shortens it per artifact. |
| Pruning | Delete stale artifacts and workflow runs from the Actions tab (deletion is permanent — and audited as artifact.destroy); delete wrong Memory facts; remove obsolete instruction files. |
| Summarization | Fold long histories into the PR description and link commits and runs instead of copying them. Copilot CLI compacts automatically at about 80% of the context window, or on demand with /compact. |
| Reset | When requirements change significantly, a new approach is chosen or assumptions are invalidated: rewrite the PR description, or close and recreate the PR; start a fresh CLI session with /clear or /new; delete the misleading memories. |
- name: Upload plan and evidence
uses: actions/upload-artifact@v7
with:
name: agent-evidence-${{ github.sha }}
path: |
plan.json
reports/
retention-days: 30 # shorter than the repository default of 90 3.2 Persist agent state and manage context drift
Capture progress and decisions as durable artifacts
Memory tells an agent what matters; state records what has been done, what was decided and what remains. In GitHub, state is not in one place — it is spread across artifacts that together act as persistent memory:
- The issue holds requirements and acceptance criteria.
- The pull request is the state anchor: task description, link to the issue, current plan, progress updates and decisions — GitHub aggregates commits, checks and discussion there.
- Commits represent incremental progress.
- Workflow runs capture validation results on every push.
Copilot cloud agent keeps the PR title and body current as it iterates, and its commit messages link back to the
session log. Copilot CLI persists each session under ~/.copilot/session-state/ (checkpoints, a
plan.md, created files), which is what makes --resume and --continue work.
Resume without repeating steps or diverging
flowchart LR OPEN["Open the existing PR"] --> READ["Re-read description<br/>and linked issue"] READ --> COMMITS["Check commits<br/>already pushed"] COMMITS --> CHECKS["Check the Checks tab<br/>latest results"] CHECKS --> CONTINUE["Continue from<br/>the latest state"]
| Surface | How to resume |
|---|---|
| Copilot cloud agent | Mention @copilot on the PR, or continue the session from the Agents page — it works on the same branch with the same context |
| Custom agents | A PR keeps using the agent profile version (commit SHA) it started with, so a later profile edit cannot change behaviour mid-PR |
| Copilot CLI | --continue resumes the most recent session in the directory; --resume / /resume opens a picker or takes a session ID or name |
| Copilot SDK | resumeSession(sessionId) — conversation, plan and artifacts are persisted; API keys and in-memory tool state are not |
// Copilot SDK. A session is only resumable if you give it your own ID —
// otherwise the SDK generates a random one you cannot find again.
await client.createSession({ sessionId: "alice-pr-214-review", model: "gpt-5.4" });
// Later, from a new client instance or after a restart:
const session = await client.resumeSession("alice-pr-214-review");
await session.sendAndWait({ prompt: "Continue with step 3 of the plan." });
// State lives in ~/.copilot/session-state/alice-pr-214-review/
// checkpoints/ conversation snapshots
// plan.md the agent's planning state
// files/ artifacts the agent created Detect and correct drift
Context drift is when the agent's actions stop matching the original goal or earlier decisions — common in long, multi-step runs. Watch for:
- PR changes that do not satisfy the acceptance criteria.
- Commits that contradict decisions recorded in the PR or ADRs.
- Files changed outside the agreed scope.
- Required checks failing or, worse, missing.
flowchart TB SIG["Drift signal<br/>criteria unmet · decision contradicted · scope creep · checks failing"] --> ANCHOR["Re-anchor to the source of truth<br/>issue · PR description · instructions"] ANCHOR --> COMPARE["Compare changes<br/>with acceptance criteria"] COMPARE --> UPDATE["Update the PR description<br/>or steer the session"] UPDATE --> RERUN["Push a fix and re-run checks"]
# .github/workflows/scope-check.yml — flags drift outside the agreed paths
name: Scope check
on:
pull_request:
permissions:
contents: read
jobs:
scope:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
- name: Fail on files outside the allowed paths
run: |
allowed='^(src/|tests/|package(-lock)?\.json$)'
outside=$(git diff --name-only "origin/${{ github.base_ref }}...HEAD" | grep -Ev "$allowed" || true)
if [ -n "$outside" ]; then
echo "::error::Changes outside the agreed scope:"
echo "$outside"
exit 1
fi Steer early
On a running cloud agent session, a short follow-up prompt ("Use the existing ErrorHandler class instead of new try/catch blocks") is applied after the current tool call — far cheaper than letting the session finish and reworking the PR. In the CLI, rewind to the prompt where things went wrong rather than piling corrections on top.
3.3 Ensure continuity of memory and state across tools and environments
Share agent state
Work often starts in an IDE, continues in the CLI and finishes in a cloud agent session. Share state through durable references — issue and PR URLs, branch names, commit SHAs, workflow run links — that every environment can resolve, not by copying context between chats.
flowchart LR IDE["IDE agent mode"] --> PR CLI["Copilot CLI"] --> PR CCA["Copilot cloud agent"] --> PR PR["Pull request #214<br/>branch · commits · checks · decisions"] --> ISSUE["Issue #198<br/>requirements · acceptance criteria"]
/delegate(or an&prefix) in Copilot CLI hands the task to cloud agent, committing local changes as a checkpoint on a new branch first.- Cloud agent sessions are shared with repository collaborators by default; local CLI and IDE sessions are private unless you share them, and synced sessions can be searched from Copilot Chat.
- Copilot Memory is shared across cloud agent, code review and the CLI for the same repository.
Prevent conflicting context
Conflicting context is the same information in several places with different values. Give each type of information one source of truth, update the original instead of making copies, and never restate acceptance criteria in prompts — link the issue.
| Where instructions can clash | How Copilot resolves it |
|---|---|
| Personal, repository and organization instructions | All relevant sets are provided; personal has highest priority, then repository, then organization |
Several AGENTS.md files | The nearest file in the directory tree takes precedence |
| Custom agents with the same name | Repository overrides organization, which overrides enterprise |
| MCP configuration at several levels | Out-of-the-box, then custom agent, then repository settings — later overrides earlier |
Prevent stale context
Stale context is outdated information used as if it were current. Typical causes and fixes:
| Cause | Prevention |
|---|---|
| The PR branch is behind its base | Update the branch before continuing; a ruleset can require branches to be up to date before merge |
| Checks reflect an older commit | Re-run workflows after every push; read the latest run on the Checks tab |
| Requirements changed but the issue did not | Update the issue first, then point the agent at it |
| A remembered fact no longer holds | Copilot Memory validates citations against the current branch; delete wrong facts; unused ones expire in 28 days |
| A very long session | Compaction summarizes the history; start a fresh session for a new phase of work |
Always re-anchor to GitHub
The consistent answer to "the agent picked up where another tool left off and did the wrong thing" is to make it read the current GitHub state — the issue, the PR, the latest commits and check results — rather than to transfer a longer chat transcript. For evaluation signals built on that state, continue with Skill 4.