Manage memory, state, and execution

The smallest skill area by weight, but the one that explains why long agent runs go wrong. Know where each kind of information should live, how Copilot remembers and forgets, how to resume from GitHub state instead of chat history, and how to spot and correct drift.

Skill 3 10–15% of the exam Skills measured: study guide revision of May 4, 2026
Three objectives in this skill area:

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
The memory hierarchy. The session's working context is the smallest and shortest-lived; long-term memory (instructions, skills, Copilot Memory) is curated and reused; external memory — issues, pull requests, docs and workflow artifacts — is the durable source of truth everything else defers to.
TierWhat it holdsLifetimeGitHub examples
Short-termThe current task's instructions, recent feedback, tool results, next stepsOne session — lost, or compacted, when it endsThe context window of a cloud agent or CLI session
Long-termCurated, reusable knowledge: conventions, key decisions, repeatable proceduresAcross tasks and sessionsCustom instructions, AGENTS.md, skills, custom agent prompts, Copilot Memory
ExternalThe durable record: requirements, plans, decisions, resultsAs long as the artifact existsIssues, 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

InformationStore it inWhy
Requirements and acceptance criteriaThe issueThe agent can revisit the goal and validate against it
Plan and decisionsPR description or an ADR in docs/Keeps work consistent across sessions without re-interpretation
Conventions and validation rulesRepository custom instructionsApplied automatically to every task
Rules for part of the codebasePath-specific instructions with applyTo, or a nested AGENTS.mdOnly loaded where relevant
Repeatable proceduresAgent skills (SKILL.md plus scripts)Loaded on demand, not on every request
Execution resultsWorkflow logs and uploaded artifactsDurable, linkable evidence
Facts the agent works out for itselfCopilot MemoryLearned over time; validated before use
CredentialsAgents secrets — never memory, instructions or promptsSecrets 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 factsUser-level preferences
ContentCoding conventions, architecture decisions, build commands, project rulesHow a specific user likes to work with Copilot
Created byActivity of users with write access who have Memory enabledThat user's own interactions
Available toEveryone with Memory access to that repository — and only in that repositoryOnly that user, across repositories
Stored withCitations to the supporting code, checked against the current branch before useCitations that may include the user's own words
Managed byRepository owners review and delete them (Settings → Copilot → Memory)The user; on Business/Enterprise, admins can export (JSONL) or delete them
Used by code review?YesNo — 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 excludeAgent to keep a file away from code review or cloud agent.
  • Place nested AGENTS.md files 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.
.github/instructions/payments.instructions.md
---
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

RuleMechanism
ExpirationCopilot 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.
PruningDelete 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.
SummarizationFold 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.
ResetWhen 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.
yaml
- 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"]
Resuming from GitHub state: the agent (or a person) re-reads the record rather than re-deriving it.
SurfaceHow to resume
Copilot cloud agentMention @copilot on the PR, or continue the session from the Agents page — it works on the same branch with the same context
Custom agentsA 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 SDKresumeSession(sessionId) — conversation, plan and artifacts are persisted; API keys and in-memory tool state are not
Copilot SDK
// 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"]
Correcting drift means re-anchoring to the source of truth, not arguing with the agent's latest reasoning.
yaml
# .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"]
Every surface re-anchors to the same pull request and issue, so none of them needs another's session history.
  • /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 clashHow Copilot resolves it
Personal, repository and organization instructionsAll relevant sets are provided; personal has highest priority, then repository, then organization
Several AGENTS.md filesThe nearest file in the directory tree takes precedence
Custom agents with the same nameRepository overrides organization, which overrides enterprise
MCP configuration at several levelsOut-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:

CausePrevention
The PR branch is behind its baseUpdate the branch before continuing; a ruleset can require branches to be up to date before merge
Checks reflect an older commitRe-run workflows after every push; read the latest run on the Checks tab
Requirements changed but the issue did notUpdate the issue first, then point the agent at it
A remembered fact no longer holdsCopilot Memory validates citations against the current branch; delete wrong facts; unused ones expire in 28 days
A very long sessionCompaction 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.