Architecture · Applied AI

Harnesses: Building Structured Context for Agents

The patterns to turn a generic language model into a specialized, replicable, and versionable assistant — with concrete examples of skills, chaining, memory, and privacy.

The Problem

Calling a language model via API or chat is simple. But there's a hidden cost: each invocation is isolated. The model doesn't know who you are, doesn't remember previous context, doesn't understand your domain's constraints.

You could put all of this into a prompt manually every time. It works once. It works twice. But it doesn't scale: it becomes inconsistent, hard to maintain, impossible to reuse in another context.

A harness is the structured solution to this problem: a versioned context layer — profile, skills, memory, and workflows — that lives next to your code, not inside an ephemeral prompt.

The Six Blocks of a Harness

Every functional harness is composed of six well-defined layers:

1. Profile

Defines the agent's identity: role, tone, security constraints, domain context. Feeds the system prompt of each session.

2. Skills

Discrete, documented behaviors. Each skill has: trigger (when to activate), pre-conditions, numbered steps, expected output, pitfalls.

3. Canonical Prompts

Invocation templates that ensure consistency. Examples: new-session, new-feature, code-review.

4. Memory

What persists between sessions. Can be structured and explicit (files the agent consults) or dynamic (updated during the session).

5. Session Harness

Initialization workflow. Before any work, it injects context: who the user is, what the current state is, what decisions have been made.

6. Agent

The composition of the five blocks above, instantiated with a specific role and domain.

Insight: A harness is not sophisticated code. It's intelligent organization of context — mostly Markdown, mostly documentation. The sophistication lies in knowing what to document, not in building something technically complex.

Anatomy of a Skill

The unit of work in a harness is the skill. It isn't code: it's a Markdown document with five required parts. Below, a real skill from the repository, concept-to-code, which turns an abstract concept into annotated code:

---
name: concept-to-code
description: Conceito abstrato -> implementacao comentada (TS/Python).
version: 0.1.0
---

# Concept to Code

## Trigger
O usuario diz "nao estou entendendo X" sobre um conceito abstrato.

## Pre-condicoes
- O conceito foi nomeado explicitamente.
- A linguagem-alvo e conhecida (default: TypeScript).

## Passos
1. Reformular o conceito em uma frase.
2. Escrever a MENOR implementacao que o demonstra.
3. Comentar apenas as linhas que carregam a ideia central.
4. Mostrar um caso de uso e um contra-exemplo.

## Output esperado
Bloco de codigo executavel + 3 a 5 linhas de explicacao. Sem teoria solta.

## Pitfalls
- Codigo longo demais: passando de ~20 linhas, o conceito se perde.
- Explicar a sintaxe em vez do conceito.

Each part has a job: the trigger tells the agent when to activate the skill; the pre-conditions prevent running without what's needed; the steps make the behavior repeatable; the expected output pins the format; the pitfalls encode mistakes already made so they don't recur. The practical effect: quality doesn't depend on who's operating — it depends on the skill being well-defined.

Three Concrete Skills

To validate the architecture, we built three skills with this same anatomy:

SkillTriggerOutput
concept-to-codeDoesn't understand an abstract conceptAnnotated implementation in TS/Python
exam-simulatorWants to practice for an examPractice test with annotated answer key
session-plannerLacks a defined focusPlan prioritized by urgency + interest

Orchestration Patterns

How multiple skills compose within a session:

Simple Routing

The harness routes to the correct skill based on user intent. Transparent, easy to debug.

Chaining

The output of one skill becomes the input to the next. Context accumulates along the chain.

Meta-skill

A skill that knows when to call others. Rarely necessary — if you need to chain more than 3 skills, the design is probably wrong.

Chaining in Practice

The pattern becomes concrete in a chained harness, exam-prep-session. User input: "I have an exam on logic gates and Karnaugh maps in three days and I don't know where to start." The chain runs three skills, each consuming the previous output:

  1. session-planner reads memory (priorities, topic gaps) and returns a 3-block plan: review logic gates, practice Karnaugh simplification, final mock exam.
  2. concept-to-code takes the weak concepts from the plan and generates, for each, an annotated implementation (e.g., simulating logic gates in TypeScript) — abstract becomes tangible.
  3. exam-simulator takes the studied material and produces a mock exam with an annotated answer key, closing the review loop.

None of the three skills knows the others exist. The session harness composes them — which is why each skill stays independently testable and reusable.

Memory in Three Layers

A harness without memory acts like a generic assistant. The memory we use has three layers, separated by how often they change:

Splitting by change frequency isn't cosmetic: it defines what to reload each session (the session layer) and what to treat as near-constant (the stable one). A skill like session-planner depends critically on this structure — without it, there's nothing to prioritize.

Memory That Improves with Use

The three layers above answer what persists. But there's a deeper question: how does memory get better over time, instead of merely accumulating? The inspiration came from the Hermes architecture (Nous Research), studied as a reference — not installed. Two mechanisms were adapted.

1. A curated, always-injected memory (MEMORY.md)

A single file read at the start of every session. Not a raw log: it's the distillation of insights, patterns, and decisions. And it's bounded — at most ~50 entries. When it fills up, you remove a stale entry before adding a new one. The bound is the point: it's not a warehouse, it's a living summary. In practice, the file's own header carries its usage contract:

# Memory

Status: canonical
Bounded: max ~50 curated entries - distill, do not just append.
Inject at the start of every session.

## Key concepts
- Harness = profile + skills + memory + workflows.
- Context engineering > prompt engineering: what enters the
  context, and when, matters more than the instruction text.
- Tool scoping: fewer exposed tools = better performance.

## Discovered patterns
- Dual memory (Hermes): MEMORY.md (bounded, always injected)
  + session history (searchable, queried on demand).
- Session-end distillation: extract 1-3 high-quality insights
  on close - not the raw transcript.

## Open questions
- Curator: automatic cron vs. manual checklist?

2. Distillation at session-end

On close, the agent runs a short workflow (session-end) and asks itself: what did I learn that I didn't know before? What reusable pattern emerged? What would I get wrong again if I didn't record it now? It then writes 1 to 3 high-quality entries — never the entire conversation transcript. The workflow isn't loose prose; it's a procedure with explicit curation rules:

# Harness: Session End

## 1. Distillation into MEMORY.md
Ask:
- What did I learn today that I didn't know yesterday?
- What reusable pattern emerged?
- What would I get wrong again if I didn't document it now?

Curation rules:
- At most 1-3 new entries per session.
- If MEMORY.md > 50 entries: remove 1 stale entry before
  adding a new one.
- DISTILLED entries (principle/pattern), not transcript.
- Prefer updating an existing entry over duplicating.

## Curation (every ~5 sessions)
- Merge overlapping entries; remove stale ones.
- Archive questions already answered.

Why bound the memory: injecting everything degrades the model's ability to follow instructions — the context rot phenomenon — even with huge context windows. More context isn't more intelligence; curated context is. An append-only memory turns into noise; a distilled memory gets sharper.

The curator pattern closes the loop: every ~5 sessions, you audit MEMORY.md — merge overlapping entries, drop what's no longer true, archive questions already answered. It's the same principle Hermes applies automatically with a weekly cron; here, it becomes a manual checklist. The difference between a harness that stagnates and one that compounds lives in this ritual.

Monorepo Structure

A single harness is a directory with docs, agents, skills, and workflows. Multiple harnesses coexist in a monorepo sharing common skills:

harnessStudy/
├── harness-template/       # Reusable skeleton
├── harness-study/          # Meta-harness (learning harnesses)
├── harness-builder/        # A harness that builds other harnesses
├── cs-study-harness/       # Specific domain (education)
├── finance-harness/        # Another domain (investments)
└── skills/                 # SHARED skills
    ├── concept-to-code/
    ├── exam-simulator/
    ├── session-planner/
    └── paper-writer/

The rule that keeps this clean is simple: a skill used by more than one harness lives in the root skills/; a skill exclusive to one harness lives in <harness>/skills/. Result: zero duplication, and a new harness is born from a cp -r harness-template/.

Privacy Architecture: Private Source, Public Surface

A useful personal harness contains real context — how you learn, what you're working on. But you want to publish the learnings. These two goals seem to conflict. The solution isn't keeping two repositories; it's separating source from surface:

Why automate the guard: leak prevention that relies on human discipline eventually fails. Turned into a CI test, it fails the deploy — never your judgment on a tired day.

From Plan to Practice: the Harness Builder

Building a harness by hand means filling ~10 files — repetitive and easy to get wrong. The natural step was to turn that process into a harness: the harness-builder, a harness whose domain is creating other harnesses. It's the meta-skill idea taken to the level of the whole repository.

It runs as two chained skills, with a human checkpoint in the middle:

  1. interview-for-harness runs a four-block interview — domain, user and agent, constraints, stack and memory — and produces a reviewable summary.
  2. human checkpoint: the summary is approved before a single file is generated. Fixing the summary takes two minutes; fixing ten files built on the wrong premise takes thirty.
  3. scaffold-harness takes the approved summary and generates the full structure — docs, agent, workflows, and the first skill — shipping a MEMORY.md from day zero.

The interview is deliberately short — fewer than ten questions, grouped so the agent confirms understanding after each block before moving on:

# Skill: interview-for-harness

Block 1 - Domain
1. In one sentence: what is this harness's domain?
2. What concrete problem does it solve? Who feels it,
   when, how often?

Block 2 - User and agent
3. Who uses it? (role, context, expertise)
4. What is the agent's role? (tutor / advisor / reviewer)
5. Which 3-5 recurring tasks must it do well?

Block 3 - Constraints
6. What does the harness deliberately NOT do?
7. What sensitive data exists? How to isolate it?

Block 4 - Stack and memory
8. Which LLM/platform?
9. What persists between sessions?

-> Output: an Interview Summary, reviewed by the user
   BEFORE any file is generated.

Design lesson: the most valuable part of the builder isn't the file generation — it's the interview. Separating figuring out what to build from building it makes mistakes cheap and the result reviewable. Automation serves human judgment; it doesn't replace it.

The very investments harness — the finance-harness shown in the tree above — was born from that interview. The builder stopped being a plan and became a tool.

Design Decisions (and why)

DecisionWhyAccepted tradeoff
Markdown over codeReadable, versionable context, editable by human and agentLess "power" than code — rarely needed
No meta-orchestratorSimple routing + targeted chaining are predictable and debuggableGives up "magic" automation
Vendor- and model-agnosticThe patterns survive swapping tool or LLMNo platform-specific features
Single-file i18nOne URL, one deploy, one link to shareSlightly larger HTML

Next Iterations

The Harness Builder and the memory that distills at session-end have left the backlog and become part of the repository. What remains open:

References

This harness's architecture decisions — memory and self-improvement in particular — were informed by the following sources, studied as reference: