# Cross-Agent Shared Intelligence (Shared Context Layer) Implementation Plan

> Status note (2026-03-08): Active roadmap order, blockers, and contributor priority live in the [Engram Feature Roadmap](https://github.com/users/joshuaswarren/projects/1). This file is historical design context and may describe scope that is only partially shipped.

> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.

**Goal:** Turn a multi-agent OpenClaw installation into a coordinated team by giving all agents a shared context directory (priorities, outputs, feedback) plus daily synthesis, cross-signal amplification, and weekly compounding.

**Architecture:** File-based shared context (markdown + small JSON) as the primary coordination surface. Agents read shared-context before acting; specialized crons produce roundtable digests and cross-signal summaries. Keep it simple (files, conventions) and compatible with OpenClaw’s agent+cron model.

**Tech Stack:** TypeScript OpenClaw plugin(s), OpenClaw cron jobs, markdown + JSON files under a shared path.

---

## Resolved Decisions (So Far)
- Location strategy: hybrid.
  - Default path: `~/.openclaw/workspace/shared-context/`
  - Optional override: `sharedContextDir`
- Shipping: inside Engram (v4.0), not a separate plugin.
- Write policy: staged writes + curator merge, with a small allowlist of direct-write locations.
- Priorities source of truth: both human + automation; canonical top section curated; automated inputs append below with timestamps; curator merges.
- Direct-write allowlist: expanded.
  - Allowed direct-write:
    - `shared-context/agent-outputs/<agent>/...` (each agent owns its subdir)
    - `shared-context/staging/<agent>/...` (each agent owns its subdir)
    - `shared-context/feedback/inbox.jsonl` (append-only; strict schema)
    - `shared-context/priorities.inbox.md` (append-only; strict section format)
    - `shared-context/kpis/<agent>.json` (snapshotted; append-only or last-write-wins per file, decided later)
  - Curator-only:
    - `shared-context/priorities.md` (canonical top section)
    - `shared-context/roundtable/`
    - `shared-context/cross-signals/`

## Directory Contract (Proposed)

`shared-context/`
- `priorities.md`
- `agent-outputs/<agent>/<YYYY-MM-DD>/...`
- `feedback/<YYYY-WW>.jsonl` (append-only decisions)
- `roundtable/<YYYY-MM-DD>.md` (daily digest)
- `cross-signals/<YYYY-MM-DD>.json` (entity convergence report)
- Optional:
  - `kpis/` (snapshotted metrics)
  - `calendar/` (today’s meetings)
  - `content-calendar/`

Guiding rules:
- Append-only where possible.
- Prefer human-readable markdown.
- Keep JSON small and stable.
- Avoid secrets; no raw tool args.

---

## Component Breakdown

### Component A: Living Priority Stack

**Behavior:**
- Every agent reads `shared-context/priorities.md` at the start of a run.
- Agents should adapt work selection and output formatting based on current priorities.

**Implementation options:**
- Conventions-only (doc + templates): simplest, no plugin code.
- Helper plugin that injects priorities into system context for every agent start.

---

### Component B: Agent Outputs Dropzone

**Behavior:**
- Each agent writes its outputs to `shared-context/agent-outputs/<agent>/...`.
- Other agents read latest outputs before producing new work.

**Key design questions:**
- Output naming standard
- Retention policy
- Anti-spam constraints

---

### Component C: Feedback Loop (Shared)

**Behavior:**
- Approvals/rejections captured into append-only files under `shared-context/feedback/`.
- All agents read the last N feedback items and apply them as a constraint.

**Key design questions:**
- Where UI comes from (Discord buttons vs explicit tool calls)
- How feedback maps to behavior (rules vs soft bias)

---

### Component D: Cross-Signal Detection

**Behavior:**
- Detect entities/topics appearing across 2+ agent outputs within a time window.
- Generate `cross-signals/<date>.json` and a markdown summary section in `roundtable/<date>.md`.

**Implementation options:**
- Simple deterministic matching (entity list + normalization + counts).
- Leverage Engram v3.0 entity extraction + namespaces.
- Optional semantic enhancer (configurable, default-off): use an LLM to detect fuzzy overlap (synonyms, CEO vs person name, product vs repo name, etc.).
- Provider support: must work with any OpenClaw provider, including the existing robust local LLM path.
- Default provider behavior (when enabled): use the same provider/model selection as Engram extraction (so installs inherit the same local-vs-remote behavior and failover policy).
- Similarity: consider using existing Engram entities plus QMD similarity over recent memories/outputs to propose candidate overlaps before asking an LLM.

---

### Component E: Daily Context Sync + Weekly Compound

**Behavior:**
- Daily cron reads:
  - priorities
  - today’s agent outputs
  - recent feedback
  - recent cross-signals
- Produces:
  - `roundtable/<date>.md`
  - updated `cross-signals/<date>.json`

Weekly cron produces:
- A compact “what worked / what didn’t” doc.
- Optionally promotes curated items into shared memory (Engram v3.0 `shared` namespace).

---

## Open Questions (Answer One At A Time)

1. Where should `shared-context/` live in an OpenClaw install?
   - Decision (this install + recommended default): Option C (hybrid)
   - Default: `~/.openclaw/workspace/shared-context/`
   - Optional: `sharedContextDir` config override to an external path (symlink optional)

2. Should this ship as part of Engram (v4.0) or as a separate plugin that optionally integrates with Engram?
   - Decision: ship inside Engram (v4.0)

3. How strict should write access be?
   - free-for-all writes
   - staged writes with curator merge
   - read-only for most agents
   - Decision: staged writes + curator merge, with a small allowlist of direct-write locations (example allowlist: per-agent `agent-outputs/<agent>/...`, per-agent `staging/<agent>/...`).

4. What is the primary “priority input” source?
   - human-edited priorities.md
   - voice note -> transcription -> agent update
   - both, with explicit merge rules
   - Decision: both, with explicit merge rules (canonical top section curated; automated inputs append below with timestamps; curator merges).

---

## Non-Goals (First Cut)
- Real-time agent-to-agent messaging protocols.
- Complex orchestration/state machines.
- Building a dashboard (can be layered on later).

---

## Implementation Tasks (Execution-Grade)

### Task 1: Shared-Context Config + Path Resolution

**Files:**
- Modify: `src/types.ts`
- Modify: `src/index.ts`
- Create: `src/shared-context/paths.ts`
- Test: `tests/shared-context-paths.test.ts`

**Step 1: Write failing tests**
- Default shared-context path resolves to `~/.openclaw/workspace/shared-context/` when `sharedContextEnabled=true` and no override is set.
- When `sharedContextDir` override is set, it is used.
- Path is sanitized and never escapes (no `..` traversal).

**Step 2: Implement**
- Add config keys (all default-off):
- `sharedContextEnabled` (default false)
- `sharedContextDir` (optional override)
- `sharedContextMaxInjectChars` (cap)
- Implement `SharedContextPaths` helper to return canonical paths for:
- `priorities.md`, `priorities.inbox.md`
- `agent-outputs/<agent>/...`
- `staging/<agent>/...`
- `feedback/inbox.jsonl`
- `roundtable/`, `cross-signals/`, `kpis/`, `rubrics/`

**Step 3: Run tests**
Run: `npm test`
Expected: PASS.

---

### Task 2: Shared-Context Directory Bootstrap (Safe, Idempotent)

**Files:**
- Create: `src/shared-context/bootstrap.ts`
- Modify: `src/orchestrator.ts`
- Test: `tests/shared-context-bootstrap.test.ts`

**Step 1: Write failing tests**
- `bootstrapSharedContext()` creates required directories when enabled.
- It does not overwrite existing files.

**Step 2: Implement**
- Create directories:
- `shared-context/agent-outputs/`, `shared-context/staging/`, `shared-context/feedback/`, `shared-context/roundtable/`, `shared-context/cross-signals/`, `shared-context/kpis/`, `shared-context/rubrics/`
- Create empty templates if missing:
- `priorities.md` (with a “CANONICAL (curator)” header)
- `priorities.inbox.md` (append-only instructions)

---

### Task 3: Write Policy Enforcement (Staging + Allowlist)

**Files:**
- Create: `src/shared-context/policy.ts`
- Test: `tests/shared-context-policy.test.ts`

**Step 1: Define allowlist (expanded, locked)**
- Direct-write allowed:
- `agent-outputs/<agent>/...`
- `staging/<agent>/...`
- `feedback/inbox.jsonl` (append-only, strict schema)
- `priorities.inbox.md` (append-only, strict format)
- `kpis/<agent>.json` (snapshot file semantics; decide LWW vs append-only per file)
- Curator-only:
- `priorities.md`, `roundtable/`, `cross-signals/`

**Step 2: Implement**
- `assertSharedContextWriteAllowed(path, mode, agentId)` where mode includes `appendOnly|overwriteAllowed`.
- Enforce append-only for inboxes (open file with append and reject truncation).

---

### Task 4: Shared-Context Read Injection (Priorities + Optional Roundtable)

**Files:**
- Modify: `src/index.ts`
- Create: `src/shared-context/read.ts`
- Test: `tests/shared-context-injection.test.ts`

**Behavior**
- In `before_agent_start`, if `sharedContextEnabled`:
- read `priorities.md` (cap by chars)
- optionally read today’s latest `roundtable/<YYYY-MM-DD>.md` (cap)
- inject as a compact “Shared Context” section.
- Must be timeboxed + fail-open.

---

### Task 5: Agent Output Writer Tool (Direct-Write Allowlisted)

**Files:**
- Modify: `src/tools.ts`
- Create: `src/shared-context/outputs.ts`
- Test: `tests/shared-context-outputs.test.ts`

**Tool**
- `shared_context_write_output`
- Params:
- `agent` (default from sessionKey principal/agent mapping or explicit)
- `title`
- `body` (markdown)
- `tags` (optional)
- Writes to `shared-context/agent-outputs/<agent>/<YYYY-MM-DD>/<slug>.md`
- Adds a small frontmatter/header block with timestamp + provenance.

---

### Task 6: Daily Curator Job (Staging Merge + Roundtable)

**Files:**
- Create: `src/shared-context/curator.ts`
- Modify: `src/tools.ts`
- Test: `tests/shared-context-curator.test.ts`

**Tool**
- `shared_context_curate_daily`
- Behavior:
- reads staging submissions
- updates canonical `priorities.md` (top section only)
- writes `roundtable/<date>.md`
- clears/archives merged staging items (do not delete; move to `staging-archive/`).
- Must never post to Discord; cron delivery should be `none`.

---

### Task 7: Cross-Signal Detection (Deterministic + Optional Semantic Enhancer)

**Files:**
- Create: `src/shared-context/cross-signals.ts`
- Modify: `src/tools.ts`
- Test: `tests/shared-context-cross-signals.test.ts`

**Deterministic baseline**
- parse entities/topics from agent outputs using a simple schema:
- `Entities:` section (one per line) or a short JSON header.
- count overlap across distinct agents.

**Optional semantic enhancer (default-off)**
- Config:
- `crossSignalsSemanticEnabled` (default false)
- `crossSignalsSemanticTimeoutMs`
- Provider selection: reuse Engram extraction provider selection and failover rules.
- Flow:
- propose candidate overlaps via deterministic + QMD similarity
- optionally ask LLM to merge fuzzy duplicates + add explanations.

**Outputs**
- `cross-signals/<YYYY-MM-DD>.json`
- include provenance: which files/agents contributed to each signal.

---

### Task 8: Daily Sync Cron Surface (No Auto-Register By Default)

**Files:**
- Modify: `src/index.ts`
- Modify: `README.md`

**Behavior**
- Provide recommended cron snippet (agentTurn calling `shared_context_curate_daily` + `shared_context_cross_signals_run`).
- If auto-register is ever added, it must be default-off and must create `isolated/agentTurn` jobs only.

---

### Task 9: Docs + Verification

**Files:**
- Modify: `README.md`
- Create: `docs/shared-context.md`

**Verification**
Run:
```bash
npm test
npm run check-types
npm run build
```
Expected: PASS.
