← the whole session plugin/skills/compact-agentic-session/SKILL.md

Create and consume agent session compactions for cross-session continuity. Use when capturing or retrieving intent.

Agent Session Compactions — Quick Functions

A "compaction" is a written record of one Claude Code session: what the person wanted, what got built, what's still open, and the lessons worth keeping. Without it, the next session (or the next agent) starts blind — it has to guess what you meant instead of reading what a previous agent already understood and you already corrected.

Where the record lives — pick one, and it works either way:

  • If you've set up your own service for this (see /alignment-harness:harness-setup), record it there — POST/GET at whatever endpoint you configured, using whatever auth it needs.
  • Otherwise (the default, works with nothing extra installed): write it as a JSON file. alignment-harness records compactions prints the folder — write one file per session, named <sessionId>.json. Everything below that would otherwise be a network call becomes a file read/write instead. Nothing about the quality bar changes; only where the record is stored.

The rest of this skill assumes the local file store unless you say "if you have your own API" — read those branches only if you built one.

Get the answer

Want to know... Local default If you have your own API
All compactions ls $(alignment-harness records compactions) GET <your endpoint>/compactions
Search by keyword grep -ril "<keyword>" $(alignment-harness records compactions) GET .../compactions?search=...
Filter by repo/project grep -l '"repo": *"<name>"' $(alignment-harness records compactions)/*.json GET .../compactions?repo=...
This session's compaction cat $(alignment-harness records compactions)/$(alignment-harness session-id).json GET .../compactions/by-creator-session/$SESSION_ID
Which sessions lack a compaction compare ~/.claude/projects/<project>/*.jsonl session ids against filenames in the records folder GET .../compactions/non-logged

Do something

Want to do... Local default If you have your own API
Create/update a compaction Write (or merge into) $(alignment-harness records compactions)/<sessionId>.json POST .../agent/compact body: {sessionId, compactedSession, title, ...}
Add a comment Append to a comments array in that same file POST .../compactions/:sessionId/comments
Delete a compaction Delete the file DELETE .../compactions/:sessionId
Backfill missing session ids See "Session ID Auto-Attach" below POST .../compactions/backfill-creator-session-ids

Canonical helper: write-and-report

Use this whenever you need to write or update the current session's compaction AND show the result in the conversation immediately. It writes the local file first (always works, no setup needed) and only reaches for your own API if you've configured one.

writeAndReportCompaction() {
  local session_id="$1"
  local title="$2"
  local compacted_session="$3"
  local extra_json="${4:-{}}"

  local dir; dir="$(alignment-harness records compactions)"
  local file="$dir/${session_id}.json"

  jq -n --arg sessionId "$session_id" --arg title "$title" \
        --arg compactedSession "$compacted_session" --argjson extra "$extra_json" \
        '{sessionId:$sessionId,title:$title,compactedSession:$compactedSession} + $extra' > "$file"

  echo "COMPACTION WRITTEN: $session_id"
  echo "$file"

  # Optional: if you configured your own API in the switches file, also POST it there.
  if [ -n "$OWN_COMPACTION_API_URL" ]; then
    curl -s -X POST "$OWN_COMPACTION_API_URL" -H "Content-Type: application/json" -d "@$file" >/dev/null \
      && echo "also posted to $OWN_COMPACTION_API_URL"
  fi
}

Required use:

  • Call this instead of a raw file write when the person should see proof that the compaction was saved.
  • The line COMPACTION WRITTEN: <sessionId> (or, if you're using your own API, whatever it returns as a sessionId) MUST stay visible in the conversation.
  • Lightweight background research agents should use this same helper for completion updates, post-plan updates, and blocker updates — one door in, so records don't fragment across ad-hoc writes.

Recovery — never silently swallow a failure

Local file store (default): a write either happens or the command errors. After writing, read the file back and confirm it parses and has the fields you just wrote. If it's missing or malformed, say so plainly and retry — never claim "saved" without having read it back.

If you're using your own API: if the POST returns a connection error, empty response, or a non-2xx status: retry once. If it fails again, print COMPACTION_BLOCKED: <your API> unreachable — writing the local file instead and fall through to the local file store above so the record isn't lost. Restarting your own dev server, if that's the fix, is on you — this skill doesn't assume any particular process manager.

Never silently swallow a compaction failure. If neither the local file nor your API produced a confirmed write, the compaction did not save — say that out loud.

Looking things up across sessions

If you've set up institutional-memory search (/alignment-harness:harness-setup checkpoint "memory-search"), use it first — it searches your own past sessions and this repo's notes for you. If you haven't set it up, grep works fine: grep -ril "<keywords>" $(alignment-harness records compactions) for saved compactions, and grep -l "<keywords>" ~/.claude/projects/*/*.jsonl for raw session history. Say plainly when a search finds nothing, rather than guessing.


Agent Session Compactions — Full Lifecycle Skill

What This System Is

Agent session compactions are structured summaries of Claude Code agent work sessions. They capture:

  • Overarching intent — the big-picture goal of the session
  • Target UX intent — the specific testable outcome delivered, in "when X, then Y" terms
  • Success measure — how to verify the work achieved its goal, naming 1-2 real, checkable measures (primary + secondary)
  • UX stories brought to reality — conversational descriptions of what changed
  • Incomplete items — work that was started but not finished (with status/priority)
  • Principles — "When X then Y" statements extracted from the session
  • How to consume — step-by-step instructions to verify/use the work

Important: this is for AGENT (Claude Code) session compactions — records of what an agent did. If your project separately records end-user sessions (e.g. support conversations, coaching sessions, customer calls), that's a different system; don't conflate the two.

Architecture (local default)

Layer Location Purpose
Store one JSON file per session, in the folder from alignment-harness records compactions the record itself — sessionId, 15+ structured fields, a short human-readable id if you want one
Lookup grep/jq over that folder, or your own script list, search, filter
Viewer none by default — the JSON file, or your own admin page if you build one reading/triaging records
Search the harness's local memory-search (optional, see harness-setup), or your own semantic index finding a compaction by meaning rather than exact words

If you've built your own API + database for this (see the "Get the answer" / "Do something" tables above), swap the "Store" row for your own model and routes, and "Viewer" for your own admin UI — nothing else in this skill changes.

When to Create a Compaction

Create a compaction when a session involved:

  • 3+ meaningful file changes (not just formatting)
  • 1+ new patterns, principles, or architectural decisions
  • Work on a feature that spans multiple sessions
  • Debugging that uncovered a non-obvious root cause
  • Any incomplete work that a future agent needs to pick up

Do NOT compact trivial sessions (single typo fix, config change, etc.).

Scope Declaration (write before writing code)

When the person assigns work, write a scope declaration BEFORE writing any code — the reading of what they want, and how sure you are. The harness's prompt hook (if you've wired it up per /alignment-harness:harness-setup) puts that record back in front of you on every prompt.

Format:

{
  "sessionId": "$SESSION_ID",
  "compactedSession": "scope declaration",
  "scopeDeclaration": {
    "intent": "{the exact, precise, context-bound intended outcome — include specific conditions, who experiences it, what changes from today}",
    "certainty": 85,
    "decomposed": [
      "When {condition} → {expected outcome}",
      "When {condition} → {expected outcome}"
    ],
    "boundary": "{what is explicitly NOT in scope}",
    "verification": "{how we'll know it's done — runnable commands}",
    "assumptions": ["{what must be true for this to work}"]
  }
}

Steps:

  1. Decompose the person's intent into testable statements
  2. Write the scope via this skill's local file (or your own API) — one place, so nothing fragments
  3. Translate the scope into plain language (see /speak-human if you have it, or just write it conversationally) and print it to the person
  4. THEN proceed with implementation

Rules:

  • Write the scope BEFORE starting implementation — it's your contract with the person
  • certainty is not confidence in your ability — it's confidence you understand WHAT THE PERSON WANTS
  • If certainty is under 90, run /reflect (if shipped) or otherwise pause and reason through your best guess before proceeding
  • UPDATE the compaction when scope changes (the person gives new information, or you discover something)

Certainty scale:

  • 95-100: the person was explicit, requirements are unambiguous
  • 85-94: clear intent but some details need assumptions — state and validate them
  • 70-84: general direction clear but specifics fuzzy — reflect, then proceed with your best prediction
  • Below 70: predict the most likely intent, propose it as a default assumption and proceed. Don't stall work waiting for an answer to something you can reasonably guess and then correct.

UX Criticality and Pre-Execution Reflection

Before composing the compaction, run ux-criticality-measurement if the work was user-facing. If the criticality score is 4+, also run ux-pre-execution-reflection and include both outputs in the compaction's uxCriticality and preExecutionReflection fields.

Voice and Translation Rules (MANDATORY)

Translation Philosophy

"Translation" means converting code changes into intent and outcome language, not implementation language. Never lead with technical jargon. Always translate to the underlying intent: who is affected, what moment in their experience, what steps lead to it.

Example of good translation:

"A lot of features have a switch for whether they're visible to everyone yet, and we handle that with a feature-flag wrapper. If something shouldn't reach the public, it's marked in-development so only admins see it — that's the one canonical place that decision gets made. Here, some code was quietly bypassing that canonical switch for one feature. We fixed it so the flag is respected the same way everywhere, instead of one feature having its own private exception."

Conversational Framing (MANDATORY)

All human-facing output MUST use conversational framing, NOT jargon-first formal language.

WRONG:

"When an admin expands a record, the original conversation is loadable above the reasoning section so they can cross-reference what was actually said while reviewing the analysis."

RIGHT:

"Ok so I was working on a tool that lets you check how well our summary of a conversation actually captures it. What I fixed was its ability to pull up the right original conversation next to the summary. Check if it worked by..."

  • If you have a viewer for these records (your own admin UI, an Obsidian note, etc.), give the person the full clickable path or URL, not a relative one, on its own line at the bottom of the message.
  • If you're using the local file store with no viewer, give the person the file path instead ($(alignment-harness records compactions)/<sessionId>.json) so they can open it directly.

How to Create a Compaction

Compaction Depth Calibration

Before composing, decide how rich this compaction needs to be. If you scored this task with alignment-harness score (see /alignment-harness:governer), use its band:

Score band (from alignment-harness score) What to include What to skip
low stakes (<20) Title, 1-sentence overarching intent, 1-2 UX stories, incomplete items only agentReasoning, principles, preExecutionReflection, uxCriticality
moderate (20-59) All required fields, key decisions captured preExecutionReflection, uxCriticality (unless user-facing)
high (60-79) Everything including principles with reasoning, uxCriticality if user-facing Nothing — full coverage
top band (80+) Everything + a /reflect-style prefix, all principles with full reasoning chain, delivery-chain analysis Nothing — maximum detail

If you didn't score the task, default to standard/moderate coverage.

Execution Order (MANDATORY)

  1. Generate agentReasoning FIRST — the 5 self-reflection fields below. This surfaces gaps that inform all other fields.
  2. Deduce overarching intent — what larger goal was this part of? Where is the energy going? (e.g. "reducing time-to-first-value for new users", "giving admins clear visibility into a process that used to be invisible")
  3. Deduce success measures — name 1-2 real, checkable measures (primary + secondary) for this initiative, in outcome terms
  4. Atomic intent gate — count your "When X, then Y" statements across targetUxIntentTitle, incompleteItems[].intentStatement, and uxStoriesBroughtToReality. If fewer than 2 testable statements exist, decompose further before proceeding.
  5. Compose remaining fields informed by the reasoning
  6. Attach the real session id — run alignment-harness session-id. NEVER use a custom slug or a hallucinated id — it must be the real Claude Code session id, so concurrent sessions don't collide and so a later agent can actually find this record by session.
  7. Print AGENT_COMPACT DONE when the write (or POST) succeeds

Child Progress Updates (MANDATORY)

When you need to preserve phase-level, requirement-level, or subtask-level progress under an existing compaction, keep the signal but use the compliant shape:

  • Keep the parent compaction on its real session id
  • Attach the child signal under the parent via subCompactions[]
  • Optionally link with parentCompactionIds, but only when the child record itself is also a real session id
  • NEVER invent synthetic child session ids like <id>-phase1, <id>-S1, <id>-child, or any suffixed custom slug

Allowed:

  1. Update the parent compaction directly using the parent's real session id
  2. Attach a child progress object to the parent via subCompactions[]

Forbidden:

  • Creating a new top-level compaction record whose sessionId is a fake child slug. That produces orphaned, unfindable records.

Identify and Compact

Identify the following context to compact, and create a compacted item that keeps all the nuance around the most critical things to learn:

  • What was the person seeking to do? What was the overarching intent and why were they seeking to do that? What larger goal did this connect to, and how?
  • What strategies, workflows, or approaches were used? What testable statements can you derive about what was actually intended?
  • Did you learn anything from the session?
  • Condense the session's conversation to reveal the person's intent, the sub-intents used to realize it, how it would be validated, and the actual outcome created — with specific paths or strategies.

Compaction Format Goal

  • Nested headings that are nuanced and crystal clear about specific intent
  • All critical learnings surfaced, what changed and why, decisions made, organized into modular items with a descriptive title
  • Strip out noise, refine just the signal, with acute specificity about the person's actual intent
  • Never assume the reader will know what you're talking about or in which context what you're saying is true
  • Derive or deduce the overarching goal this was part of and the intent behind it
  • Derive or deduce what would measure success and what success would look like in real terms
  • Make the title so clear that, by simply looking at it, the reader instantly knows what it's about

Atomic Intent Decomposition (MANDATORY — enforced before filing)

Every compaction MUST decompose the session's work into atomic, testable intent statements. This is not optional polish — it's what lets a later agent find and act on this work instead of having to re-read the whole record.

Required fields for every compaction:

  1. overarchingIntentTitle — The big-picture goal. Specific enough that an agent can tell whether new work relates to it. Bad: "Improve admin tools". Good: "Turn session records into something the next agent actually reads before guessing."
  2. targetUxIntentTitle — The specific testable outcome this session delivered, as a "When X, then Y" conditional. Bad: "Fixed the page". Good: "When someone opens the records list, they see the real content without the page crashing".
  3. incompleteItems[].intentStatement — Every incomplete item MUST have an intentStatement: a present-tense promise describing correct behavior when the task is done. Written as: "When {actor} does {action}, they experience {outcome}".
  4. uxStoriesBroughtToReality — Each story captures what was actually delivered this session.

Self-check before filing: count your atomic intent statements. If the compaction has fewer than 2 testable "When X, then Y" statements across all fields, you haven't decomposed enough. Go back and extract more signal from the session.

Writing the record — local file (default)

SESSION_ID="$(alignment-harness session-id)"
FILE="$(alignment-harness records compactions)/${SESSION_ID}.json"
cat > "$FILE" <<'EOF'
{
  "agentReasoning": {
    "gestaltObservation": "",
    "alignmentFailures": "",
    "sanityCheckSteps": "",
    "surfacingQuestion": "",
    "surfacingAnswer": ""
  },
  "sessionId": "<id>",
  "dateCreated": "2026-xx-xx",
  "dateOfOriginalSession": "2026-xx-xx",
  "repo": "<your repo or project name>",
  "title": "Human-readable title describing the outcome",
  "subtitle": "One-line context",
  "overarchingIntentTitle": "The big-picture goal — where the energy is going",
  "overarchingIntentDescription": "When {constraints} we {testable outcome}",
  "successMeasure": "How to verify, naming 1-2 real measures (primary/secondary)",
  "targetUxIntentTitle": "Specific promise",
  "targetUxIntentDescription": "When {someone does X} they {experience Y}",
  "howToConsumeThisWorkProduct": "Conversational framing + sanity check + the file path or link",
  "uxStoriesBroughtToReality": [
    {
      "story": "Short outcome — under 100 chars, plain language, no jargon",
      "status": "complete",
      "verbatimOriginQuote": "The exact words the person said that originated this intent",
      "fulfillmentReasoning": "Why this change fulfills the scope — 1-2 sentences, plain language",
      "generatedBy": "opus"
    }
  ],
  "incompleteItems": [
    {
      "title": "Short, outcome-first, under 80 chars",
      "status": "pending",
      "priority": 70,
      "intentStatement": "When {actor} does {action}, they experience {outcome}",
      "domain": "example-domain-tag",
      "verbatimUserQuote": "exact quote from the person that originated this item",
      "extractionConfidence": "high",
      "generatedBy": "opus",
      "humanImpact": {
        "affectedUsers": "who is affected",
        "currentExperience": "what happens today",
        "fixedExperience": "what happens once this is done",
        "changesByUserType": "how it differs by kind of user, if it does"
      },
      "currentStateVerification": {
        "verifiedStillBroken": true,
        "verificationMethod": "how you checked",
        "verificationNote": "what you found"
      },
      "nextStep": "concrete next action",
      "blockers": "none",
      "complexity": 25
    }
  ],
  "principles": [
    {
      "title": "Short human-readable name — under 60 chars, no code/jargon/line numbers",
      "content": "Full explanation of why this principle exists and when it applies (can be long)",
      "scope": "When {X constraint} then {Y behavior}",
      "status": "pending",
      "priority": 70,
      "leverageScore": 85,
      "tags": ["example-tag"]
    }
  ],
  "uxCriticality": {
    "criticalityScore": 6.5,
    "isUserFacing": true,
    "dimensions": {
      "silentFailureDegradation": 7,
      "deliveryChainLength": 5,
      "firstImpressionWeight": 8,
      "harmIfWrong": 6
    },
    "reasoning": "Explain why each dimension scored the way it did",
    "reflectionRequired": true,
    "reflectionLevel": "full"
  },
  "preExecutionReflection": {
    "targetIntent": "When {someone} does {action}, they experience {outcome}",
    "deliveryChain": [
      { "layer": "Layer Name", "servesOrFights": "serves", "note": "Why" }
    ],
    "failureModes": ["Silent failure mode 1"],
    "uxRequirements": ["Must X", "Must Y"],
    "harmPotential": "How this could cause more harm than good",
    "riskyAssumption": "The assumption most likely to be wrong",
    "metaQuestion": "The question I should be asking",
    "metaAnswer": "The answer to that question"
  },
  "compactedSession": "Full markdown content of the compaction",
  "tags": ["example", "tags", "here"]
}
EOF
echo "COMPACTION WRITTEN: $SESSION_ID"
echo "$FILE"

If you've configured your own API instead, POST this same JSON body to whatever endpoint you set up.

After writing or updating a compaction, print the file path so the person can open it directly:

📎 <the path printed above>

If you built your own viewer, print its URL to this record instead.

Compliant Parent-Attached Child Example

If you need to preserve child progress as signal, attach it to the parent instead of inventing a fake child session — update the same file, adding a subCompactions[] entry:

{
  "sessionId": "<parent id>",
  "title": "Example: multi-phase refactor — parent record",
  "compactedSession": "Parent compaction body...",
  "subCompactions": [
    {
      "title": "[Phase 1] Example phase name",
      "agentType": "attached-child-compaction",
      "taskDescription": "What this phase did",
      "description": "Phase-level progress attached to the parent compaction.",
      "status": "completed",
      "governerScore": 85,
      "planStatus": "posted"
    }
  ]
}

Agent Self-Reasoning (MANDATORY — generate FIRST before composing)

Before generating any compaction fields, you MUST first reason through and populate these 5 agentReasoning fields:

  1. gestaltObservation — What would it take to observe the whole picture and state the actual intent clearly enough that the person would instantly recognize it and know whether you got it right?
  2. alignmentFailures — Where did the work go against what the existing code already intended? Where did you create dependencies that didn't need to exist, or break something by assuming instead of checking?
  3. sanityCheckSteps — The simplest steps to actually verify the work, written so a human can do them without reading code.
  4. surfacingQuestion — The question that, if you asked it of yourself, would surface the signal in this work over the noise.
  5. surfacingAnswer — The honest answer to that question.

These are the agent's structured self-reflection — not filler, but an honest look at alignment gaps and verification steps. Generate them FIRST; the reasoning surfaces gaps that should inform incompleteItems, successMeasure, and howToConsumeThisWorkProduct.

Field-Specific Requirements

howToConsumeThisWorkProduct

Must follow this structure:

  1. Conversational intro — "Ok so I was working on [what] which [why it matters]..."
  2. What I did — specific changes in plain, outcome-first terms
  3. Simplest sanity check — "Check if it worked by [doing this], noticing [result]. If [good sign], it's working. If [bad sign], something's off."
  4. 1 sentence for the main outcome you were trying to create
  5. The record's file path or link, on its own line

uxStoriesBroughtToReality

Each story is a structured object with 3 REQUIRED fields:

  1. verbatimOriginQuote — The exact words the person said that originated this intent. Copy-paste from the conversation. If you can't find a direct quote, use the closest paraphrase and note it.
  2. story — The change that fulfilled that intent. Short, under 100 chars, plain language. No code paths, no line numbers, no endpoint names.
  3. fulfillmentReasoning — Why that change fulfilled the scope. 1-2 sentences in plain language connecting what was asked to what was built.

Also include: status ("complete", "partial", "pending", "blocked"), generatedBy ("opus", "sonnet", "haiku", "human")

Example — GOOD:

{
  "verbatimOriginQuote": "I can't tell which parts of this were AI-generated vs which I wrote myself",
  "story": "Each record now shows which model generated each part of it",
  "fulfillmentReasoning": "Without attribution the person couldn't tell which fields to trust. Adding a source tag per section lets them gauge confidence at a glance.",
  "status": "complete",
  "generatedBy": "opus"
}

Example — BAD:

{
  "story": "Added enrichmentHistory rendering to RecordCard component with source-specific color coding via a utility function"
}
  • Do NOT include aspirational/planned changes — only what's actually live
  • HARD LIMIT: story MUST be under 100 characters
  • NO code paths, NO line numbers, NO endpoint names in story

incompleteItems (UNIFIED MODEL — tasks AND proposals)

incompleteItems is the single model for all actionable items: proposed changes, incomplete tasks, approved work, completed work. The status field determines the lifecycle stage — not separate arrays.

Status lifecycle: proposed → pending → approved → actionable → completed (or dismissed / rejected at any stage)

Proposals: when proposing a change, file it as an incompleteItem with status: "proposed", rather than a separate structure — one model, one place to look.

Required fields for EVERY item regardless of status:

  • title — outcome-first, under 80 chars. Not code jargon.
  • intentStatement — "When {actor} does {action}, they experience {outcome}". MANDATORY.
  • verbatimUserQuote — exact quote from the person that originated this item. MANDATORY.
  • domain — searchable tag (e.g. "auth", "billing", "onboarding")
  • priority — 1-100 integer
  • status — one of: proposed, pending, approved, actionable, completed, dismissed, rejected, implemented
  • generatedBy — "opus", "sonnet", "haiku", or "human"
  • extractionConfidence — "low", "medium", or "high"

Principle Quality Gate (MANDATORY)

Principles in the principles[] array must meet ALL of these criteria:

  • title starts with "When {condition/constraint}" — making it conditional and testable
  • content is minimum 500 characters — a full paragraph explaining the reasoning, the evidence that established it, and how to apply it across situations
  • content includes a "Why:" section explaining what happened that crystallized this principle
  • content includes a "How to apply:" section explaining when this principle fires and what to do differently
  • tags array has at least 2 domain tags for cross-domain discoverability

Principle format — WRONG:

{
  "title": "New systems are always additive",
  "content": "Never interpret anything as replacing an existing system unless explicitly told to."
}

Principle format — RIGHT:

{
  "title": "When building anything new that overlaps with an existing system, treat it as additive — never a replacement — unless explicitly told to replace it",
  "content": "When an agent encounters an existing system that partially overlaps with what it's being asked to build, it must frame the new thing as complementary rather than a replacement. Example from a real correction: the person said 'never interpret anything as replacing, ever — remember that, unless I ask for that explicitly.' Why: existing systems carry accumulated value that isn't always visible from the outside, and different systems often serve different purposes even where they overlap. Destroying that value by silently 'replacing' it is irreversible and usually wrong. How to apply: whenever proposing or building something new, name what existing systems it sits alongside. Use language like 'adds a new layer,' 'complements,' 'sits alongside.' Never use 'replaces,' 'supersedes,' 'instead of' unless explicitly asked for.",
  "tags": ["agent-behavior", "additive-systems"]
}

Vague one-sentence principles are worse than no principles — they give future agents false confidence that they understand a rule while providing zero actionable guidance. A principle that doesn't say WHEN it fires, WHY it exists, and HOW to apply it will be reinterpreted into whatever meaning is convenient for whoever reads it next.

Required structured subdocuments:

  • humanImpact — who is affected, what they see today, what they'd see after the fix, what changes per user type
  • currentStateVerification — when you checked, whether it's still broken, how you checked, what you found

Required for proposals (status = proposed):

  • before — what exists today
  • after — what would change
  • evidenceOfAlignment — quotes or signals from the person confirming this is wanted
  • evidenceOfFix — measurable outcome after applying

Optional enrichment fields: nextStep, blockers (or "none"), complexity (1-100), content (additional context).

successMeasure

  • Say how you would measure success for this initiative in real, checkable terms.
  • Name 1 or 2 real measures you believe would be the best primary and secondary signal for the value of this intent.
  • Example: "Primary: signup-to-first-action rate (measures whether the simplified flow actually reduces friction). Secondary: time-to-first-action (measures whether people engage faster)."

overarchingIntentTitle / overarchingIntentDescription

  • Sense or deduce what larger goal this work was part of.
  • Surface where the energy is going — be specific.
  • Examples: "Increasing retention through a smoother first-week experience", "Giving admins clear visibility into a process that used to be a black box".

Alignment check (MANDATORY before writing): ask yourself: "Does this describe what the project/organization wants to achieve, or what THIS TASK does?" If it describes the task, rewrite it. The field must answer "what larger goal does this work serve?" — not "what did I do?"

If you have a company/project-intent store (see company-intent-db or intent-db if shipped, or your own equivalent), check it before filling this field; otherwise state your best inference and mark it unconfirmed.

Wrong: "Shipped a re-engagement email for inactive users" Right: "Recover engagement from lapsed users as a growth lever before spending more on acquisition"

Required Fields

  • sessionId — the real Claude Code session id, from alignment-harness session-id. Never a custom slug like "claude-code-20260306-73111" or a synthetic child id like "<id>-phase1" — these break re-launch and produce orphaned records.
  • compactedSession — full markdown content
  • title, overarchingIntentTitle, targetUxIntentTitle — make it findable
  • agentReasoning — structured self-reflection (5 fields above), generated BEFORE composing other fields
  • principles[] — first-order concerns for future agents
  • incompleteItems[] — so nothing gets lost
  • howToConsumeThisWorkProduct — so a human can verify

How to Find Compactions

If you've set up institutional-memory search (/alignment-harness:harness-setup), use it. Otherwise: grep -ril "<query terms>" $(alignment-harness records compactions).

Local file listing with filters

DIR="$(alignment-harness records compactions)"
ls "$DIR"                                        # all compactions
grep -ril "<keyword>" "$DIR"                      # search by keyword
grep -l '"repo": *"<name>"' "$DIR"/*.json         # filter by repo/project

If you've configured your own API, use the equivalent list/search endpoints there instead.

How to Act on Compaction Findings

Incomplete Items

  1. Check status — pending items need triage, approved items need execution
  2. Create a task or start a session to complete the work
  3. Update status to completed when done

Principles (FIRST-ORDER CONCERNS)

Principles are "When X then Y" statements that encode hard-won learnings. They MUST be:

  • Stored with full context — not just the rule, but WHY it exists
  • Tagged for discoverability — use tags relevant to your project's domains (e.g. ["ux", "security", "performance"])
  • Scored for leverage — leverageScore 0-100, where 100 = affects every session
  • Promoted when high-leverage — principles with leverageScore >= 70 should be added to relevant skill files as rules, or to your project's CLAUDE.md if they're universal. If you have an intent-tracking store (intent-db or similar), propose them there too.

Principle title vs content rules (MANDATORY)

  • title = short human-readable name, under 60 characters, NO code paths, NO line numbers, NO jargon
  • content = the full explanation with context and reasoning (can be as long as needed)
  • The title must be scannable at a glance
  • Good title: "Always validate data completeness, not just required fields"
  • Bad title: "The write endpoint accepts structured data but only validates minimum required fields — see the handler at line 88..."
  • If your title contains a colon followed by a long explanation, you've put content inside title — move it

UX Stories

These are human-readable descriptions of what changed. Use them in commit messages, PR descriptions, changelogs.

Discoverability Audit Checklist

When creating or reviewing compactions, verify:

  • Title clearly describes the outcome (not just the technical change)
  • Principles have a scope field in "When X then Y" format
  • Principles have a leverageScore assigned
  • Incomplete items have priority assigned
  • Incomplete items have an outcome-first title
  • Tags include the repo/project name and domain keywords
  • howToConsumeThisWorkProduct has actionable steps, ending in a real file path or link (not a vague description)
  • successMeasure names 1-2 real, checkable measures

Session ID Auto-Attach (MANDATORY — the session id MUST NOT be empty)

What is the session id?

The Claude Code session id is a UUID that uniquely identifies one Claude Code terminal session. It's the key that links a compaction back to its originating session — without it, the record is an orphan: unfindable by session, and if you have a re-launch feature it has nothing to resume.

How to get it — alignment-harness session-id, not a shared file

Run alignment-harness session-id. It resolves in order: --session if you passed one, then CLAUDE_CODE_SESSION_ID (set by Claude Code itself), then the last session a hook saw. Don't read a shared "current session id" file that every concurrent agent writes to — if two sessions run at once, that file holds whichever one wrote last, not the one asking. Multiple agents running at once means every one but the most recent writer gets the wrong id.

SESSION_ID="$(alignment-harness session-id)"
echo "Session ID: $SESSION_ID"

Why this matters

  • Re-launch, if you build it: an admin UI can use the session id to relaunch an agent with the full context of that compaction
  • Session tracing: you can pull every compaction from one terminal session by that id
  • Without it: the compaction is an orphan — unfindable by session, un-resumable

Verification checklist

After writing a compaction, read it back and verify it contains a non-empty session id that looks like a real UUID, not null, empty, or a custom slug. If it's wrong, the detection failed — check how you called alignment-harness session-id.

Completion Signal

When the compaction write (or POST) succeeds, print on separate lines:

AGENT_COMPACT DONE
<the local file path, or your own viewer's URL to this record>

If you build your own API for this

Register its endpoints in your own tools registry (see agentic-tooling-registry if shipped) so agents can find them the same way they'd find any other tool. The original build this skill came from used paths like <your-api>/compact (create/update), <your-api>/compactions (list), <your-api>/compactions/:id (get), <your-api>/compactions/:id (delete, DELETE method), <your-api>/compactions/:sessionId/comments (add comment) — treat these as an example shape, not a fixed contract.

Lessons learned building this (apply the same way to a local file or a database)

  1. The identifying field is the session id, not an auto-generated row id — look things up by session id everywhere.
  2. Update means replace-the-relevant-fields, not append — if you're using PUT/PATCH semantics against your own API, know which one your server implements.
  3. compactedSession is required — always set it, even if the real content lives in other fields, because some consumers key off its presence.
  4. incompleteItems[] REQUIRED FIELDS — every item MUST have: title (under 80 chars, outcome-first), intentStatement, verbatimUserQuote, domain, priority, generatedBy, extractionConfidence, and a humanImpact subdoc with all 4 fields. If you're using a schema-validated database, fields missing any of these can get silently stripped on save without warning — write the record, then read it back, and compare field counts.
  5. principles[] QUALITY GATE — every principle MUST have: title starting with "When {condition}", content minimum 500 chars with Why + How to apply sections, and tags array with 2+ domain tags. Vague one-liners are worth rejecting.
  6. Write-then-read verification — after every write, read the record back and compare field counts. If any incompleteItems lost their title/intentStatement/humanImpact, the write silently dropped them somewhere. Report the discrepancy — don't silently proceed.

Example from real-world use (opt-in illustration — not something to replicate as-is)

A full pass over every past compaction (a "discoverability audit") once found real value in an existing record store: dozens of records had principles worth extracting that had never been pulled out, and one record turned out to be an orphan with no session id at all — unreachable by any lookup. The lesson generalizes: periodically sweep your own store for records missing required fields or a session id, and repair them, the same way you'd run a data-quality check on any other store.

Cross-References

  • Admin UI patterns: your own admin-tooling patterns, if you have any (an equivalent to admin-tooling-templates-full-stack if you ship one)
  • Intent lifecycle: intent-lifecycle skill
  • Agent tooling registry: agentic-tooling-registry skill (if you register your own API endpoints there)
  • Discoverability audit: discoverability-audit-learnings-findable-by-agents skill
  • A different kind of session record: if your project separately compacts end-user sessions (support, coaching, calls), that's a distinct system from this one — keep them separate even if the schema looks similar