# How AIOS Agents Communicate Using Story Files and Pass Context

> Discover how AIOS agents communicate using story files and share context seamlessly via a session state file. Learn about agent interaction in SynkraAI/aios-core for efficient workflow.

- Repository: [SynkraAI/aios-core](https://github.com/synkraai/aios-core)
- Tags: internals
- Published: 2026-02-16

---

**AIOS agents communicate by reading and writing to a shared session state file ([`.aios/session-state.json`](https://github.com/SynkraAI/aios-core/blob/main/.aios/session-state.json)) while using markdown story files in `docs/stories/` as the human-readable specification of current work, enabling seamless context passing between agents like `@dev`, `@qa`, and `@po`.**

In the SynkraAI/aios-core repository, the AIOS (Artificial Intelligence Operating System) architecture treats every agent activation as a continuable session rather than an isolated command. The system bridges human intent and machine execution through **story files**—markdown documents that define tasks, acceptance criteria, and status—while a JSON-based session state ensures agents remember what the previous agent accomplished.

## The Story-Driven Communication Architecture

AIOS uses a dual-layer persistence model to maintain context across agent boundaries.

**Story files** serve as the canonical description of work. Located under `docs/stories/`, these markdown files contain structured fields like `**Status:** In Progress` or `**Status:** Done`, along with acceptance criteria and implementation notes. Agents reference the `storyPath` to understand the scope of their current task.

**Session state** provides the transient memory. The [`.aios/session-state.json`](https://github.com/SynkraAI/aios-core/blob/main/.aios/session-state.json) file stores machine-readable metadata including the previous agent ID, the last 10 commands executed (`lastCommands`), the active workflow (`workflowActive`), and the current story file path (`currentStory`).

## How Context Flows Between AIOS Agents

The `SessionContextLoader` class in [`.aios-core/core/session/context-loader.js`](https://github.com/SynkraAI/aios-core/blob/main/.aios-core/core/session/context-loader.js) orchestrates the handoff protocol. When an agent starts, the loader reads the JSON state, generates a natural-language summary, and makes it available to the new agent.

### Step 1: Loading Session State with SessionContextLoader

When an agent like `@qa` is invoked, the system instantiates `SessionContextLoader` and calls `loadContext(agentId)`.

```javascript
// Inside any agent module (e.g. agents/dev.js)
const SessionContextLoader = require('../core/session/context-loader');
const loader = new SessionContextLoader();

function activateAgent(agentId) {
  // Pull the whole context for this activation
  const ctx = loader.loadContext(agentId);
  console.log('🔎 Session context →', ctx);
  // ctx contains: previousAgent, lastCommands, workflowActive, currentStory …
}
activateAgent('dev');

```

The method extracts the previous agent, command history, and active workflow from [`.aios/session-state.json`](https://github.com/SynkraAI/aios-core/blob/main/.aios/session-state.json).

### Step 2: Formatting the Greeting

The loader converts the raw JSON into a human-readable greeting via `formatForGreeting()`.

```javascript
const loader = new SessionContextLoader();
const greeting = loader.formatForGreeting('qa');   // current agent = @qa
process.stdout.write(greeting);

```

Typical output:

```text
📍 Session Context: Continuing from @dev (Dev) activated 7 minutes ago
   Last action: *validate-story-draft
   Recent commands: *create-story, *validate-story-draft, *develop
   ⚡ Active Workflow: story_development

```

This greeting appears in the console when the agent activates, immediately informing the user (and the agent's own reasoning loop) of the session's history.

### Step 3: Consuming Context in the SuggestionEngine

The `SuggestionEngine` in [`.aios-core/workflow-intelligence/engine/suggestion-engine.js`](https://github.com/SynkraAI/aios-core/blob/main/.aios-core/workflow-intelligence/engine/suggestion-engine.js) consumes the loaded context to tailor its recommendations.

```javascript
// Inside SuggestionEngine (lines 121-128)
const context = {
  lastCommands: sessionState.lastCommands,
  storyPath: sessionState.currentStory,
  workflowActive: sessionState.workflowActive,
  // … additional enrichment
};

```

The engine uses `storyPath` to verify that suggestions align with the current story's acceptance criteria, while `lastCommands` prevents redundant recommendations.

### Step 4: Persisting State After Task Completion

When an agent finishes a task, it calls `onTaskComplete()` to update the session state.

```javascript
// Called by the orchestrator after a task completes
const loader = new SessionContextLoader();

function taskFinished(taskName, result) {
  // result = { success: true, agentId: 'dev', storyPath: '/path/to/story.md' }
  loader.onTaskComplete(taskName, result);
}
taskFinished('develop', { success: true, agentId: 'dev', storyPath: 'docs/stories/v2.1/sprint-10/story-wis-3.md' });

```

This method:
- Appends the task to `lastCommands` (keeping only the 10 most recent)
- Updates `currentStory` if the task was bound to a story file
- Infers the new workflow state via `_inferWorkflowState()`
- Writes the updated JSON back to [`.aios/session-state.json`](https://github.com/SynkraAI/aios-core/blob/main/.aios/session-state.json)

## Working with Story Files and Session State

Story files follow a markdown structure with metadata fields that agents parse to understand task scope.

A typical story file located at [`docs/stories/v2.1/sprint-10/story-wis-3.md`](https://github.com/SynkraAI/aios-core/blob/main/docs/stories/v2.1/sprint-10/story-wis-3.md) contains:

```markdown

# Story: WIS-3 Implement Context Loader

**Status:** In Progress
**Assignee:** @dev
**Sprint:** 10

## Acceptance Criteria

- [ ] SessionContextLoader loads previous agent data
- [ ] Greeting format includes last 3 commands
- [ ] State persists to .aios/session-state.json

```

The **Status** field acts as a state machine trigger. When a developer changes `**Status:**` to `In Progress`, the worktree hook in [`.aios-core/infrastructure/scripts/story-worktree-hooks.js`](https://github.com/SynkraAI/aios-core/blob/main/.aios-core/infrastructure/scripts/story-worktree-hooks.js) can automatically create a dedicated Git worktree for isolated development.

## Advanced Context Patterns

### Overriding Story Paths via CLI

Agents can switch contexts without terminating the session by using the `--story` flag.

```bash

# CLI (aios) – force a different story for the current suggestion run

aios suggest --story docs/stories/bugfix-123.md

```

The `SuggestionEngine` receives this override at lines 33-40 and replaces the loaded `context.storyPath` with the user-specified path, allowing agents to pivot to urgent bug fixes while preserving command history and workflow state.

### Git Worktree Integration

The story-driven architecture extends to repository management. The [`story-worktree-hooks.js`](https://github.com/SynkraAI/aios-core/blob/main/story-worktree-hooks.js) script demonstrates how story status changes trigger infrastructure automation.

```javascript
// Inside .aios-core/infrastructure/scripts/story-worktree-hooks.js
await onStoryStart(projectRoot, storyPath, { force: true });

```

When a story moves to `In Progress`, this hook reads the story ID, checks the worktree manager, and creates an isolated Git worktree. This ensures that agents working on different stories operate in completely separate directory contexts while still sharing the same [`.aios/session-state.json`](https://github.com/SynkraAI/aios-core/blob/main/.aios/session-state.json) for continuity.

## Summary

- **Story files** in `docs/stories/` provide human-readable specifications with status metadata that drives agent behavior.
- **[`.aios/session-state.json`](https://github.com/SynkraAI/aios-core/blob/main/.aios/session-state.json)** acts as the shared memory layer, storing the last 10 commands, previous agent ID, active workflow, and current story path.
- **`SessionContextLoader`** in [`.aios-core/core/session/context-loader.js`](https://github.com/SynkraAI/aios-core/blob/main/.aios-core/core/session/context-loader.js) manages the read/write lifecycle, generating natural-language greetings via `formatForGreeting()` and persisting updates via `onTaskComplete()`.
- **`SuggestionEngine`** consumes session context to tailor recommendations based on the active story and command history.
- **CLI overrides** (`--story`) and **Git worktree hooks** extend the context system to support story switching and isolated development environments.

## Frequently Asked Questions

### How do AIOS agents know what the previous agent did?

AIOS agents retrieve the previous agent's actions by reading [`.aios/session-state.json`](https://github.com/SynkraAI/aios-core/blob/main/.aios/session-state.json) through the `SessionContextLoader` class. The JSON file stores the `previousAgent` ID, the `lastCommands` array (containing up to 10 recent tasks), and the `workflowActive` state. When a new agent starts, `formatForGreeting()` transforms this data into a human-readable summary that appears in the console greeting.

### Can agents switch to a different story without losing session history?

Yes, agents can switch stories while preserving command history and workflow state by using the `--story` CLI flag. When you run `aios suggest --story docs/stories/bugfix-123.md`, the `SuggestionEngine` (lines 33-40) overrides the `storyPath` in the context object but retains the `lastCommands` and `previousAgent` data from [`.aios/session-state.json`](https://github.com/SynkraAI/aios-core/blob/main/.aios/session-state.json). This allows seamless pivoting to urgent tasks without session reset.

### What is the maximum number of commands stored in the session state?

The session state retains exactly the 10 most recent commands in the `lastCommands` array. This limit is enforced by the `onTaskComplete()` method in `SessionContextLoader` (lines 73-89), which appends new tasks to the array and truncates it to maintain only the newest 10 entries. This prevents the JSON state file from growing indefinitely while preserving enough history for meaningful context.

### How do story files trigger automated Git worktree creation?

Story files trigger Git worktree automation through status metadata and the [`story-worktree-hooks.js`](https://github.com/SynkraAI/aios-core/blob/main/story-worktree-hooks.js) script. When a developer updates a story's `**Status:**` field to `In Progress`, the hook detects the change and invokes `onStoryStart(projectRoot, storyPath, { force: true })`. This creates an isolated Git worktree dedicated to that story, ensuring that agents working on different stories operate in separate directory contexts while sharing the same session state.