Design Document

Session Artifacts

Persistent, queryable outputs for agent sessions in Agent Orchestrator

Author: Agent Orchestrator Team Status: Draft Date: 2026-03-11 Revision: 1.0

1. Executive Summary

Agent Orchestrator spawns parallel AI coding agents that work autonomously on issues. Today, when a session completes or is killed, its work products vanish with the worktree. The only persistent record is a flat key=value metadata file in the archive directory, which captures status, branch, and PR URL — but nothing about what the agent actually produced.

Session Artifacts are a new first-class concept: persistent, metadata-rich outputs that any session can create during its lifetime. Artifacts survive session cleanup, are queryable by the orchestrator and web dashboard, and restore context when a session is revived.

Goals

Design principle: Artifacts are the session's memory. They are what a session knows and what it produced — the bridge between ephemeral agent context and persistent project knowledge.

2. Current System Analysis

How Sessions Work Today

A session lifecycle in Agent Orchestrator follows this path:

spawn() --------> workspace.create() --------> runtime.create() --------> agent launches | | | git worktree tmux session claude-code / codex / ... created at created with runs inside worktree ~/.ao/{hash}/ unique name worktrees/{id} ... agent works autonomously ... kill() ---------> runtime.destroy() --------> workspace.destroy() ------> metadata archived | | | tmux session worktree removed flat file moved to killed (git worktree remove) sessions/archive/

Current Data Structure

~/.agent-orchestrator/{hash}-{projectId}/ ├── .origin # config path for collision detection ├── sessions/ │ ├── int-1 # key=value metadata (active session) │ ├── int-2 # another active session │ └── archive/ │ ├── int-1_2026-03-10T... # archived metadata after kill │ └── int-3_2026-03-09T... ├── worktrees/ │ ├── int-1/ # git worktree (full repo clone) │ └── int-2/ └── feedback-reports/ # existing artifact-like concept └── bug_report_2026-03-10.json

Session Metadata Format

Each session file (sessions/int-1) contains flat key=value pairs:

project=integrator
worktree=/Users/foo/.agent-orchestrator/a3b4c5d6e7f8-integrator/worktrees/int-1
branch=feat/INT-1234
status=working
tmuxName=a3b4c5d6e7f8-int-1
pr=https://github.com/org/repo/pull/42
issue=INT-1234
agent=claude-code
createdAt=2026-03-10T14:00:00.000Z
runtimeHandle={"id":"a3b4c5d6e7f8-int-1","runtimeName":"tmux","data":{}}

What Is Missing

GapImpact
No artifact storage Agent produces a PRD, changelog, or design doc — it lives only in the worktree, which is deleted on kill
No work summary persistence After cleanup, no record of what files the agent changed, what decisions it made, or why
Restore has no context When ao session restore runs, the restored agent starts cold with no memory of prior work
Orchestrator is blind Parent orchestrator cannot query "what did session int-3 produce?" — only status/PR URL
Cross-session knowledge lost Insights from one session (e.g., "API uses GraphQL not REST") cannot inform sibling sessions
No audit trail for code changes Why was this code written this way? The agent's reasoning dies with the session

The feedback-reports system (packages/core/src/feedback-tools.ts) is the closest existing concept to artifacts. It stores JSON files with structured data (bug reports, improvement suggestions) in a project-level feedback-reports/ directory using Zod-validated schemas. However, it is not scoped to individual sessions and has a fixed schema. Session artifacts need to be more general-purpose and tightly coupled to the session lifecycle.

3. Competitive Analysis

How other orchestrators and AI coding tools handle session outputs and artifacts:

System Artifact Mechanism Storage Survives Cleanup? Queryable? Multi-session?
GSD 2.0
(TACHES)
.planning/ directory with structured markdown + YAML frontmatter. STATE.md tracks project memory across sessions. Coordinator writes artifacts to {artifacts-dir}/YYYY-MM-DD-{engine}-{desc}.md. Phase artifacts like {N}-UAT.md. The /gsd:resume-work command restores full project context from STATE.md. Local files in .planning/ (gitignored). Flat markdown + JSON config. Yes Planning artifacts persist in .planning/; agent context is discarded but file artifacts remain. Yes /gsd:resume-work reads STATE.md Partial Fresh subagent contexts read shared .planning/research/
Google ADK First-class ArtifactService interface with save_artifact(), load_artifact(), list_artifact_keys(), delete_artifact(). Named, versioned binary data. Both session-scoped and user-scoped artifacts. Path pattern: {app}/{user}/{session}/{filename} for session-scoped, {app}/{user}/user-scoped/{filename} for cross-session. Pluggable backends: InMemoryArtifactService (ephemeral), FileArtifactService (local disk), GcsArtifactService (Google Cloud Storage). Automatic versioning on save. Yes File and GCS backends persist across restarts. Yes Full API: list keys, load by version, delete Yes User-scoped artifacts span sessions; session-scoped are isolated
Claude Code JSONL session files at ~/.claude/projects/{encoded-cwd}/{session-id}.jsonl. Records every prompt, tool call, tool result, and response. Automatic Session Memory system extracts learnings every ~5,000 tokens. CLAUDE.md for persistent per-project instructions. SDK exposes listSessions() and getSessionMessages(). Local JSONL files + ~/.claude/history.jsonl. No explicit artifact separation from session log. Yes Session JSONL persists indefinitely. Yes SDK APIs for enumeration and reading Partial Auto-memory persists across sessions; CLAUDE.md is shared
Devin Full session replay with plans, code changes, terminal output, and browser screenshots. DeepWiki generates project documentation automatically. Status tracking (green/orange dots) on session pages. Enterprise knowledge base aggregated across all sessions. Cloud-hosted. Sessions accessible via web at app.devin.ai/sessions. Yes Cloud persistence. Full audit trail. Yes Web UI, wiki search, session browser Yes DeepWiki aggregates knowledge across all sessions
OpenHands
(OpenDevin)
Persistence directory with base_state.json (agent config, execution status, statistics, metadata) and events/ subdirectory with sequential event files. Default location: workspace/conversations/{id}/. Conversation restored by specifying same ID and persistence directory. Local files. base_state.json + numbered event files in events/. Yes Persistence directory survives process termination. Partial Restored by conversation ID, but no cross-session query API No Each conversation starts fresh; no multi-session memory
Cline VS Code extension state with checkpoints at session level. File Timeline for tracking modifications. task.md checklists for progress tracking. Export to markdown. /history command to resume past sessions. StateManager singleton with batched disk writes. VS Code extension storage APIs. Local state directory. Yes Persists via VS Code storage Partial History browsable, exportable to markdown No Per-session checkpoints, no aggregation
Aider Chat history in ~/.aider.chat.history.md. Every code change becomes a git commit with descriptive message. /diff shows all changes from a request. /undo reverts last change. Markdown file + git commits (code changes are the artifacts) Yes Git commits persist. Chat history persists. Partial git log for code history; chat history is flat text No Single-session chat history
Cursor Composer sessions with checkpoints for every code generation step. Agent status tracking (running / completed / waiting) in sidebar. Enterprise audit logs for compliance. Proprietary cloud + local state Yes Checkpoints accessible after restart Partial History accessible in Composer; enterprise audit logs Partial Agent sidebar tracks parallel operations
SWE-agent Trajectory files recording every action, observation, and thought. JSONL format with full action history. Patch files as outputs. Evaluation harness records results. Local JSONL trajectory files + patch files in output directory. Yes Trajectory files persist on disk. Partial Files readable; no structured query API No Independent trajectories per task

Key Takeaways

Design Influences

InfluenceWhat We AdoptWhat We Skip
GSD .planning/ Dedicated artifact directory, gitignored, human-readable filenames, STATE.md concept Phase-based numbering (we use session-scoped numbering instead)
Google ADK ArtifactService Formal service interface, versioning, session/project scoping, pluggable design GCS backend (file-only for now), MIME-based binary handling complexity
Claude Code session persistence Session-scoped directories, query APIs (list/read) Raw JSONL logging (we want curated artifacts, not replays)
OpenHands persistence Manifest file (base_state.json) pattern for indexing Event-based granularity, no cross-session features
Multi-agent orchestration patterns Shared folder pattern: minimal metadata in orchestrator, full content on disk Database-backed state (we stay stateless/file-based)

4. Proposed Architecture

Design Principles

  1. File-based, stateless — no database. Artifacts are files on disk with a JSON manifest, consistent with AO's flat-file metadata approach.
  2. Survive cleanup — artifacts live in a separate directory tree from worktrees and session metadata. Killing a session does not touch artifacts.
  3. Two write paths — agents create artifacts via a CLI tool (ao artifact create) or by writing to a well-known directory ($AO_ARTIFACTS_DIR). The orchestrator can also create artifacts programmatically.
  4. Indexed by manifest — each session's artifact directory has a manifest.json for fast querying without reading file contents.
  5. Content-addressable optional — for large binary artifacts, store by hash to deduplicate across sessions (Phase 3).

High-Level Architecture

+------------------------------------------------------------------+ | Agent Session | | | | Agent (claude-code / codex / aider / opencode) | | | | | +--> ao artifact create --type summary "Session completed..." | | +--> ao artifact create --type prd --file ./design.md | | +--> ao artifact create --type changelog --json '{...}' | | | | | +--> (or write files directly to $AO_ARTIFACTS_DIR) | +-------------------------------+----------------------------------+ | v +------------------------------------------------------------------+ | Artifact Storage Layer | | | | ~/.agent-orchestrator/{hash}-{project}/artifacts/ | | +-- {session-id}/ | | | +-- manifest.json (index of all artifacts) | | | +-- 001-summary.md | | | +-- 002-prd.md | | | +-- 003-changelog.json | | +-- {session-id}/ | | +-- ... | +-------------------------------+----------------------------------+ | +-------------------+-------------------+ v v v Orchestrator CLI Web Dashboard (queries child (ao artifact ls) (GET /api/sessions/ session artifacts (ao artifact {id}/artifacts) for decisions) show)

Directory Structure

~/.agent-orchestrator/{hash}-{projectId}/ ├── sessions/ # existing: session metadata ├── worktrees/ # existing: git worktrees (deleted on kill) ├── feedback-reports/ # existing: feedback tools └── artifacts/ # NEW: persistent artifacts (survives kill) ├── int-1/ # artifacts for session int-1 │ ├── manifest.json # index: list of all artifacts + metadata │ ├── 001-summary.md # work summary artifact │ ├── 002-prd.md # PRD artifact │ ├── 003-changelog.json # structured changelog │ └── 004-screenshot.png # binary artifact ├── int-2/ │ ├── manifest.json │ └── 001-design-doc.md └── int-3/ ├── manifest.json ├── 001-research-notes.md └── 002-code-changes.json

5. Data Model & TypeScript Interfaces

Core Types

These interfaces would be added to packages/core/src/types.ts:

// =============================================================================
// ARTIFACTS
// =============================================================================

/** Well-known artifact types for structured querying */
export type ArtifactType =
  | "summary"          // Work summary: what the agent did and why
  | "prd"              // Product requirements document
  | "design"           // Design document or architecture notes
  | "changelog"        // Structured list of changes made
  | "research"         // Research notes, API findings, etc.
  | "decision"         // Decision record (ADR-style: why X over Y)
  | "code-review"      // Code review notes or self-review
  | "test-report"      // Test execution results
  | "error-log"        // Errors encountered and how they were handled
  | "context"          // Saved context for session restoration
  | "custom";          // Anything else

/** Artifact type constants */
export const ARTIFACT_TYPE = {
  SUMMARY: "summary" as const,
  PRD: "prd" as const,
  DESIGN: "design" as const,
  CHANGELOG: "changelog" as const,
  RESEARCH: "research" as const,
  DECISION: "decision" as const,
  CODE_REVIEW: "code-review" as const,
  TEST_REPORT: "test-report" as const,
  ERROR_LOG: "error-log" as const,
  CONTEXT: "context" as const,
  CUSTOM: "custom" as const,
} satisfies Record<string, ArtifactType>;

/** Metadata for a single artifact */
export interface ArtifactEntry {
  /** Unique artifact ID within the session (e.g., "001", "002") */
  id: string;

  /** Artifact type for structured queries */
  type: ArtifactType;

  /** Human-readable title */
  title: string;

  /** Optional description */
  description?: string;

  /** Filename within the session artifact directory */
  filename: string;

  /** MIME type (e.g., "text/markdown", "application/json", "image/png") */
  mimeType: string;

  /** File size in bytes */
  sizeBytes: number;

  /** When the artifact was created (ISO 8601) */
  createdAt: string;

  /** When the artifact was last updated, if overwritten (ISO 8601) */
  updatedAt?: string;

  /** Session ID that created this artifact */
  sessionId: string;

  /** Project ID */
  projectId: string;

  /** Related issue identifier (if any) */
  issueId?: string;

  /** Related PR URL (if any) */
  prUrl?: string;

  /** Agent plugin that created this artifact */
  agent?: string;

  /** Free-form tags for filtering */
  tags?: string[];

  /** Version number (incremented on update) */
  version: number;
}

/** Manifest file stored at artifacts/{sessionId}/manifest.json */
export interface ArtifactManifest {
  /** Schema version for forward compatibility */
  schemaVersion: 1;

  /** Session ID this manifest belongs to */
  sessionId: string;

  /** Project ID */
  projectId: string;

  /** All artifacts in this session */
  entries: ArtifactEntry[];

  /** When the manifest was last updated (ISO 8601) */
  updatedAt: string;
}

/** Options for creating an artifact */
export interface CreateArtifactInput {
  type: ArtifactType;
  title: string;
  description?: string;
  tags?: string[];

  /** Content: provide exactly one of these three */
  content?: string;         // inline text content
  filePath?: string;        // path to file to copy into artifacts
  jsonData?: unknown;       // structured data (serialized as JSON)
}

/** Filters for querying artifacts */
export interface ArtifactFilters {
  sessionId?: string;
  projectId?: string;
  type?: ArtifactType | ArtifactType[];
  tags?: string[];
  since?: string;            // ISO 8601 lower-bound date filter
}

Artifact Service Interface

A new core service (not a plugin — artifacts are fundamental to the system):

/** Artifact service -- CRUD for session artifacts */
export interface ArtifactService {
  /** Create a new artifact for a session */
  create(
    sessionId: SessionId,
    projectId: string,
    input: CreateArtifactInput,
  ): Promise<ArtifactEntry>;

  /** List artifacts for a session (or across sessions with filters) */
  list(filters: ArtifactFilters): Promise<ArtifactEntry[]>;

  /** Read an artifact's content */
  read(
    sessionId: SessionId,
    artifactId: string,
  ): Promise<{ entry: ArtifactEntry; content: Buffer } | null>;

  /** Update an existing artifact (creates new version) */
  update(
    sessionId: SessionId,
    artifactId: string,
    input: Partial<CreateArtifactInput>,
  ): Promise<ArtifactEntry>;

  /** Delete a single artifact */
  delete(
    sessionId: SessionId,
    artifactId: string,
  ): Promise<void>;

  /** Get the filesystem path to the artifacts directory for a session */
  getArtifactsDir(
    sessionId: SessionId,
    projectId: string,
  ): string;

  /** Get artifact count for a session (fast -- reads manifest only) */
  count(sessionId: SessionId): Promise<number>;

  /** Get a text summary of what a session produced (for restore context) */
  getSessionSummary(sessionId: SessionId): Promise<string | null>;
}

6. Storage Strategy

File-Based Storage (Default)

Aligned with AO's stateless, no-database philosophy:

Manifest Format Example

{
  "schemaVersion": 1,
  "sessionId": "int-1",
  "projectId": "integrator",
  "updatedAt": "2026-03-11T14:30:00Z",
  "entries": [
    {
      "id": "001",
      "type": "summary",
      "title": "Work Summary: Implement user authentication",
      "filename": "001-summary.md",
      "mimeType": "text/markdown",
      "sizeBytes": 2340,
      "createdAt": "2026-03-11T14:00:00Z",
      "sessionId": "int-1",
      "projectId": "integrator",
      "issueId": "INT-1234",
      "prUrl": "https://github.com/org/repo/pull/42",
      "agent": "claude-code",
      "tags": ["auth", "backend"],
      "version": 1
    },
    {
      "id": "002",
      "type": "changelog",
      "title": "Changes: Added JWT auth middleware",
      "filename": "002-changelog.json",
      "mimeType": "application/json",
      "sizeBytes": 890,
      "createdAt": "2026-03-11T14:30:00Z",
      "sessionId": "int-1",
      "projectId": "integrator",
      "agent": "claude-code",
      "version": 1
    }
  ]
}

Path Utilities

New functions in packages/core/src/paths.ts:

/**
 * Get the artifacts directory for a project.
 * Format: ~/.agent-orchestrator/{hash}-{projectId}/artifacts
 */
export function getArtifactsDir(configPath: string, projectPath: string): string {
  return join(getProjectBaseDir(configPath, projectPath), "artifacts");
}

/**
 * Get the artifacts directory for a specific session.
 * Format: ~/.agent-orchestrator/{hash}-{projectId}/artifacts/{sessionId}
 */
export function getSessionArtifactsDir(
  configPath: string,
  projectPath: string,
  sessionId: string,
): string {
  return join(getArtifactsDir(configPath, projectPath), sessionId);
}

Automatic Artifact Creation

Some artifacts should be created automatically by the system at lifecycle transitions:

TriggerArtifact TypeContent
Session exits with PR summary Agent's summary (from AgentSessionInfo.summary) + PR URL + branch + files changed
Session kill/cleanup context Final session state snapshot: status, issue, PR, last activity timestamp, agent info, cost
Session restore context Restore event: when restored, from what state, what artifacts already existed
CI failure detected error-log CI check details (names, statuses, URLs) and what the agent attempted as a fix
Review comments addressed code-review Which review comments were addressed and how, with links to comment URLs

7. API Design

CLI Commands

# Create an artifact (from inside a session via $AO_SESSION_NAME)
$ ao artifact create --type summary --title "Work Summary" --content "Implemented auth..."
$ ao artifact create --type prd --file ./docs/prd.md
$ ao artifact create --type changelog --json '{"changes": [...]}'
$ ao artifact create --type decision --title "Chose JWT over sessions" \
    --content "JWT was chosen because..." --tags auth,security

# Create artifact for a specific session (from outside)
$ ao artifact create --session int-3 --type summary --title "Retrospective" --file ./notes.md

# List artifacts for a session
$ ao artifact ls int-1
  001  summary    "Work Summary: Auth implementation"     2.3 KB  2m ago
  002  changelog  "Changes: JWT middleware"                890 B   1m ago

# List artifacts across all sessions for a project
$ ao artifact ls --project integrator --type summary
  int-1/001  summary  "Work Summary: Auth"     2.3 KB  2m ago
  int-2/001  summary  "Work Summary: Payments" 1.8 KB  5m ago

# Show artifact content (prints to stdout)
$ ao artifact show int-1 001

# Export artifact to file
$ ao artifact export int-1 001 --output ./exported-summary.md

# Delete an artifact
$ ao artifact delete int-1 001

Web API Endpoints

MethodPathDescription
GET /api/sessions/{id}/artifacts List artifacts for a session. Query params: type, tags
GET /api/sessions/{id}/artifacts/{artifactId} Get artifact metadata + text content (for text types)
GET /api/sessions/{id}/artifacts/{artifactId}/raw Download raw artifact file with correct Content-Type (binary-safe)
POST /api/sessions/{id}/artifacts Create a new artifact. Body: CreateArtifactInput as JSON
GET /api/artifacts List artifacts across all sessions. Query: project, type, since, tags

Environment Variables for Agent Access

When a session is spawned, a new environment variable is set in session-manager.ts:

// Set by session-manager.ts during spawn() -- added to runtime.create() environment
AO_ARTIFACTS_DIR=/Users/me/.agent-orchestrator/a3b4c5d6-proj/artifacts/int-1
AO_SESSION_NAME=int-1  # (already exists today)
AO_DATA_DIR=...        # (already exists today)

Agents can either use the ao artifact create CLI command or write directly to $AO_ARTIFACTS_DIR. Files written directly to this directory are picked up by an on-demand manifest sync (when listing or reading artifacts) and retroactively added to the manifest.

Dashboard Integration

The session detail page (packages/web/src/app/sessions/[id]/page.tsx) gets a new "Artifacts" section showing:

New types for the dashboard in packages/web/src/lib/types.ts:

export interface DashboardArtifact {
  id: string;
  type: string;
  title: string;
  filename: string;
  mimeType: string;
  sizeBytes: number;
  createdAt: string;
  tags?: string[];
}

// Additions to existing DashboardSession interface:
export interface DashboardSession {
  // ... all existing fields unchanged ...
  artifactCount: number;           // NEW: count from manifest
  artifacts?: DashboardArtifact[]; // NEW: populated on detail page only
}

8. Lifecycle Integration

Session Spawn

// In session-manager.ts spawn():

// 1. Compute artifacts directory path
const artifactsDir = getSessionArtifactsDir(config.configPath, project.path, sessionId);

// 2. Create directory and initialize empty manifest
mkdirSync(artifactsDir, { recursive: true });
atomicWriteFileSync(
  join(artifactsDir, "manifest.json"),
  JSON.stringify({
    schemaVersion: 1,
    sessionId,
    projectId: spawnConfig.projectId,
    entries: [],
    updatedAt: new Date().toISOString(),
  }, null, 2),
);

// 3. Pass artifacts dir as environment variable to the runtime
handle = await plugins.runtime.create({
  // ... existing config ...
  environment: {
    // ... existing env vars (AO_SESSION, AO_DATA_DIR, AO_SESSION_NAME, etc.) ...
    AO_ARTIFACTS_DIR: artifactsDir,  // NEW
  },
});

Session Kill

Key design decision: kill() does NOT delete the artifacts directory. Artifacts survive session cleanup. This is the core persistence guarantee. The kill() function destroys the runtime (tmux), destroys the workspace (worktree), and archives metadata — but the artifacts/{sessionId}/ directory is untouched.

// In session-manager.ts kill():

// Before archiving metadata, create a "context" artifact with final state
try {
  await artifactService.create(sessionId, projectId, {
    type: "context",
    title: "Session Context at Kill",
    jsonData: {
      finalStatus: raw["status"],
      branch: raw["branch"],
      pr: raw["pr"],
      issue: raw["issue"],
      agent: raw["agent"],
      summary: raw["summary"],
      killedAt: new Date().toISOString(),
    },
  });
} catch {
  // Non-fatal: artifact creation should never block kill
}

// Existing kill logic continues unchanged:
// runtime.destroy(), workspace.destroy(), deleteMetadata(archive=true)

Session Restore

// In session-manager.ts restore():

// 1. Gather artifacts for context injection
const summary = await artifactService.getSessionSummary(sessionId);
const artifacts = await artifactService.list({ sessionId });

// 2. Build a restore context string from artifacts
let restoreContext = "";
if (summary) {
  restoreContext += `Previous work summary:\n${summary}\n\n`;
}
if (artifacts.length > 0) {
  restoreContext += `Available artifacts (${artifacts.length}):\n`;
  for (const a of artifacts) {
    restoreContext += `  - [${a.type}] ${a.title} (${a.filename})\n`;
  }
  restoreContext += `\nArtifacts directory: $AO_ARTIFACTS_DIR\n`;
}

// 3. Include in the agent's system prompt or post-launch message
// The prompt builder (prompt-builder.ts) can consume this restore context

Orchestrator Queries

// The orchestrator session can query child artifacts via ArtifactService:

// "What have all my child sessions produced?"
const allSummaries = await artifactService.list({
  projectId: "integrator",
  type: "summary",
});

// "What did session int-3 accomplish?"
const sessionArtifacts = await artifactService.list({ sessionId: "int-3" });

// Read the full content of a specific artifact
const result = await artifactService.read("int-3", "001");
if (result) {
  console.log(result.content.toString("utf-8"));
}

// This enables the orchestrator to make informed decisions:
// "int-3 found that the API uses GraphQL, so tell int-4 to use GraphQL too"

Lifecycle Manager Integration

The lifecycle manager (packages/core/src/lifecycle-manager.ts) can trigger automatic artifact creation on state transitions:

Session State Transitions that Trigger Auto-Artifacts: working --> pr_open Create "summary" from AgentSessionInfo.summary pr_open --> ci_failed Create "error-log" with CICheck details ci_failed --> working Update "error-log" with fix attempt info review_pending --> changes_req Create "code-review" with ReviewComment data approved --> merged Create final "summary" + "changelog" any --> killed Create "context" with full session state snapshot

9. Implementation Plan

Phase 1: Core Infrastructure MVP

Minimum viable artifact system. Agents can create artifacts, CLI can list/show them, artifacts survive kill.

1

Add types and path utilities

Files: packages/core/src/types.ts, packages/core/src/paths.ts, packages/core/src/index.ts

Add ArtifactType, ArtifactEntry, ArtifactManifest, CreateArtifactInput, ArtifactFilters, ArtifactService interfaces to types.ts. Add getArtifactsDir() and getSessionArtifactsDir() to paths.ts. Re-export new types from index.ts.

2

Implement ArtifactService

New file: packages/core/src/artifact-service.ts

File-based implementation of the ArtifactService interface. Manifest read/write with atomic writes (using existing atomicWriteFileSync). Artifact file creation and reading. Sequence number generation (001, 002, ...). Slug generation from titles. MIME type inference from file extensions. Cross-project listing by scanning artifact directories. getSessionSummary() implementation that reads the latest "summary" type artifact.

3

Integrate with session-manager

File: packages/core/src/session-manager.ts

Create artifacts directory on spawn(). Set AO_ARTIFACTS_DIR environment variable in runtime config. Create "context" artifact on kill(). Inject artifact summary on restore() via prompt builder. Ensure kill() / cleanup() never touch the artifacts directory.

4

Add CLI commands

New file: packages/cli/src/commands/artifact.ts

Modified: packages/cli/src/index.ts (register new command)

Implement ao artifact create, ao artifact ls, ao artifact show, ao artifact export, ao artifact delete. The create command auto-detects session from $AO_SESSION_NAME env var or accepts --session flag.

Phase 2: Dashboard & API Enhancement

5

Web API endpoints

New files: packages/web/src/app/api/sessions/[id]/artifacts/route.ts, packages/web/src/app/api/sessions/[id]/artifacts/[artifactId]/route.ts, packages/web/src/app/api/sessions/[id]/artifacts/[artifactId]/raw/route.ts, packages/web/src/app/api/artifacts/route.ts

REST endpoints for listing, reading, creating, and downloading artifacts. Reuse the same ArtifactService from core via the existing getServices() pattern.

6

Dashboard UI components

New files: packages/web/src/components/ArtifactList.tsx, packages/web/src/components/ArtifactViewer.tsx

Modified: packages/web/src/components/SessionDetail.tsx (add Artifacts tab), packages/web/src/components/SessionCard.tsx (add artifact count badge), packages/web/src/lib/types.ts (add DashboardArtifact, extend DashboardSession), packages/web/src/lib/serialize.ts (enrich sessions with artifact counts)

Artifacts tab on session detail page with inline markdown/JSON preview. Artifact count badge on session cards in the main dashboard.

Phase 3: Automatic Artifacts & Orchestrator Advanced

7

Lifecycle-triggered auto-artifacts

File: packages/core/src/lifecycle-manager.ts

Auto-create summary, error-log, and code-review artifacts on state transitions. CI failure details captured as artifacts with check names and URLs. Review comment handling tracked with comment URLs and resolution status.

8

Orchestrator artifact queries

File: packages/core/src/orchestrator-prompt.ts

Orchestrator session prompt enriched with child session artifact summaries. Cross-session knowledge aggregation: orchestrator can read any child's artifacts. Decision-making based on artifact content (e.g., research findings inform sibling tasks).

9

Agent workspace hooks for auto-artifact creation

Files: packages/plugins/agent-claude-code/src/index.ts, packages/plugins/agent-codex/src/index.ts, packages/plugins/agent-opencode/src/index.ts

Hook into each agent's PostToolUse or equivalent mechanism to auto-create artifacts when the agent produces significant outputs (after writing a design doc, after creating a PR, after running tests, etc.). Use the existing setupWorkspaceHooks() pattern.

10. Migration Strategy

Backward Compatibility

The artifact system is purely additive — it does not modify any existing files or behavior:

Backfilling Past Sessions

For users who want to retroactively create artifacts for already-completed sessions:

# Create a summary artifact for a past session (even if archived/killed)
$ ao artifact create --session int-3 --type summary \
    --title "Retrospective: Payment integration" \
    --content "This session implemented Stripe payment webhooks..."

# The artifact is created in artifacts/int-3/ even though int-3 is in the archive.
# The artifact service creates the directory if it doesn't exist.

Schema Versioning

The manifest includes a schemaVersion field (starting at 1). Future changes to the manifest schema will increment this version. The artifact service will include migration logic to upgrade older manifests on read, following the same defensive JSON parsing pattern used throughout AO (safeJsonParse with try/catch).

11. Open Questions & Trade-offs

Should artifacts be immutable or updatable?

Proposed: Updatable with versioning. Like Google ADK, each update to an artifact increments its version number. The previous version is not kept on disk (unlike ADK which stores all versions in GCS). Rationale: for our file-based system, keeping every version would consume significant disk space. The manifest records the current version number for audit purposes.

Alternative: Fully immutable — updates create a new artifact with a new ID. Simpler implementation but produces more files over time and makes it harder to track "the summary" vs "a summary".

How should large binary artifacts be handled?

Proposed: Direct file storage with size warnings. No content-addressable deduplication in Phase 1. The CLI warns if an artifact exceeds 10 MB. Phase 3 could add optional deduplication via content hashing for cases where multiple sessions produce the same binary output.

Risk: Disk usage could grow unbounded over many sessions. Mitigation: add a project-level artifact retention policy in Phase 3 (configurable in agent-orchestrator.yaml).

Should we integrate with the existing feedback-reports system?

Proposed: Keep them separate initially, consider unification later. Feedback reports (packages/core/src/feedback-tools.ts) are project-scoped (not session-scoped), use a fixed Zod schema, and serve a different purpose (bug reports and improvement suggestions from agents about AO itself). Artifacts are session-scoped and format-flexible.

In a future phase, feedback reports could be refactored as a special artifact type with additional Zod validation, but this is not a priority.

How do artifacts interact with the orchestrator agent's context window?

Proposed: Summaries injected, full content on demand. The orchestrator's system prompt (built in orchestrator-prompt.ts) includes a one-line summary per child session's artifacts. If the orchestrator needs full content, it uses ao artifact show as a tool call. This follows the multi-agent "shared folder" pattern: minimal metadata in the orchestrator context, full content accessible on disk.

This avoids blowing up the orchestrator's context window with artifact content from 20+ parallel sessions.

Should artifact creation be synchronous or async?

Proposed: Synchronous writes with atomic file operations. Artifacts are written to disk using the existing atomicWriteFileSync utility from packages/core/src/atomic-write.ts. The manifest is also atomically updated. This avoids needing a queue or async processing while maintaining data integrity.

The ArtifactService interface uses Promise return types for future-proofing (a remote backend could be added later), but the file-based implementation resolves synchronously under the hood.

What happens when two processes try to write artifacts simultaneously?

Proposed: Sequence number allocation with retry. Similar to the existing reserveSessionId() pattern in metadata.ts, artifact IDs use monotonically increasing sequence numbers. The manifest is read-modify-write with atomic file operations. In the unlikely event of a race (two processes reading the same sequence number), the second write detects the conflict via O_EXCL and retries with the next number.

In practice, each session has its own isolated artifacts directory, so cross-session conflicts are impossible. Within a session, only one agent process writes at a time.

Should there be artifact retention/cleanup policies?

Proposed: Not in Phase 1. Add configurable policies in Phase 3. Potential policy options in agent-orchestrator.yaml:

artifacts:
  retention:
    maxAge: 90d                    # Delete artifacts older than 90 days
    maxSizePerSession: 50MB        # Warn if a session's artifacts exceed this
    maxSizePerProject: 1GB         # Warn if project total exceeds this
    keepTypes: [summary, context]  # Never auto-delete these types

A new ao artifact prune CLI command would enforce these policies, runnable manually or via cron. The ao session cleanup command would NOT automatically prune artifacts (to preserve the persistence guarantee).

How do artifacts relate to git commits?

Proposed: Artifacts are separate from git. Like GSD's .planning/ directory, artifacts live outside the git repo in ~/.agent-orchestrator/. They are not committed. They represent the agent's working memory and outputs, not the code changes themselves.

However, structured artifact types can reference git objects:

  • A "changelog" artifact could list commit SHAs and their messages
  • A "code-review" artifact could reference PR review comment URLs
  • A "context" artifact captures the branch name and PR URL at kill time
Should artifacts be accessible as MCP tools for agents?

Proposed: Yes, in Phase 3. The setupWorkspaceHooks() method on agent plugins already configures MCP servers for Claude Code. Artifact CRUD could be exposed as MCP tools:

  • ao_artifact_create — create a new artifact
  • ao_artifact_list — list artifacts for current or other sessions
  • ao_artifact_read — read artifact content

This would let agents create artifacts natively without shelling out to the CLI.

Next step: Review this design document with the team and gather feedback. Key decisions to confirm before implementation: (1) updatable vs immutable artifacts, (2) retention policy needs, (3) priority of dashboard UI vs orchestrator integration, (4) whether MCP tool exposure should be in Phase 2 or Phase 3.