Files

279 lines
7.3 KiB
Markdown

# Bridge Spec v1.1 — Shard/Prime continuity over agentchattr
## Status
Draft v1.1 (post Prime review)
## Objective
Use `agentchattr` as shared surface + transport while keeping **Shard** and **Prime** as authoritative external runtimes.
## Non-goals (v1)
- No replacement/clone brains inside chattr
- No full shared canonical cognition state yet
- No chattr-owned memory authority
## Confirmed decisions
- Actor IDs: `dingo`, `shard`, `prime`
- Default channel: `general`
- Unmentioned messages: fanout to both `shard` and `prime`
- Runtime determines if/when to respond
---
## Design principle
Bridge treats Shard/Prime as external authoritative actors.
- chattr is not identity authority
- chattr is not memory authority
- chattr is not cognition scheduler
- chattr is UI + event stream + relay metadata
---
## Memory authority (explicit)
Priority order for memory truth:
1. Agent runtime long-term memory stores (Shard/Prime memory files + approved stores)
2. Shared source-of-truth memory repo/sync target (e.g., Nextcloud/git mirror)
3. Handoff packets (ephemeral continuity aid)
4. chattr message history (transport/UI log only)
Rule: bridge must not overwrite runtime memory directly except via normal runtime message ingestion pathways.
---
## Conversation lifecycle rules
### Start
Create new `conversation_id` when all are true:
- no explicit `reply_to` mapping to existing conversation
- no active recent binding in same channel/thread window
- no user command to attach to existing conversation
### Reuse
Reuse existing `conversation_id` when any are true:
- message replies to mapped prior message
- message belongs to mapped surface thread/job
- explicit `/conv use <id>` directive
### Fork
Fork into new `conversation_id` when any are true:
- explicit `/conv fork`
- topic switch heuristic crosses threshold (configurable)
- bridge policy marks branch due to drift conflict
### Inheritance notes
- Thread/job-local messages inherit parent conversation by default.
- New top-level channel messages may reuse recent active conversation if within idle threshold.
---
## Canonical envelope (internal)
```json
{
"version": 1,
"id": "uuid",
"ts": "2026-03-13T14:00:00Z",
"conversation_id": "conv-uuid",
"correlation_id": "corr-uuid",
"source": {
"surface": "agentchattr",
"channel": "general",
"thread_id": "optional",
"message_id": "chattr-msg-id",
"actor_id": "dingo"
},
"targets": ["prime", "shard"],
"routing": {
"mention_explicit": false,
"fanout": true,
"hop_count": 0,
"reply_to_id": null
},
"content": {
"text": "message body",
"display_text": "message body"
},
"causality": {
"parent_message_id": null,
"origin_surface": "agentchattr",
"origin_message_id": "chattr-msg-id",
"trace": ["dingo->prime", "prime->shard"]
},
"safety": {
"dedupe_key": "sha256(...)",
"ttl_sec": 600
},
"handoff": null
}
```
---
## Handoff packet (required v1)
```json
{
"handoff_version": 1,
"conversation_id": "conv-uuid",
"agent": "prime",
"source_surface": "telegram",
"target_surface": "agentchattr",
"source_thread": "telegram:chat/thread",
"task_summary": "Diagnosing bridge architecture",
"recent_context": ["..."],
"participants": ["dingo", "prime", "shard"],
"memory_refs": ["memory/2026-03-13.md"],
"origin_message_id": "telegram:1491",
"correlation_id": "corr-uuid"
}
```
### Handoff limits
- `task_summary`: max 1000 chars
- `recent_context`: max 20 items, each max 500 chars
- total handoff payload: max 16 KB
- if oversized: truncate oldest `recent_context` first, then summarize
### Handoff triggers
- first route into a new surface binding
- inactivity > 30 min
- > 40 routed msgs since last handoff
- explicit `/handoff refresh`
---
## Routing + fanout etiquette
1. Explicit mention wins
- `@prime` => prime only
- `@shard` => shard only
2. No mention => fanout both targets
3. Fanout response etiquette
- 0 responses allowed (both decide no response)
- 1 response allowed (one defers)
- 2 responses allowed (both add value)
4. Agents should avoid duplicate-value replies; prefer defer if no net-new value
5. Agent-to-agent relays should generally require explicit mention (`@other`)
---
## Loop prevention (beyond hop count)
Required controls:
- max `hop_count` (default 4)
- self-echo suppression (actor cannot receive its own emitted content back)
- causality-cycle detection via trace ring buffer
- relay cooldown per `(conversation_id, actor_pair)` window (e.g. 5s)
- dedupe via `dedupe_key` TTL index
---
## Session-aware adapter definition
A session-aware adapter MUST:
1. Inject into existing runtime identity/session path (not spawn disposable clone by default)
2. Preserve metadata: source surface/channel/thread, actor, conversation_id, correlation_id
3. Return deterministic ack/error envelope
4. Emit responses with correlation back to bridge
5. Support idempotent re-delivery by `dedupe_key`
---
## Adapter contract (HTTP v1.1)
### POST /ingest response schema
```json
{
"accepted": true,
"adapter_message_id": "adapter-msg-uuid",
"correlation_id": "corr-uuid",
"status": "queued",
"retryable": false,
"error": null
}
```
### Error schema
```json
{
"accepted": false,
"correlation_id": "corr-uuid",
"status": "rejected",
"retryable": true,
"error": {
"code": "SESSION_BUSY",
"message": "target session temporarily unavailable",
"details": {}
}
}
```
### Callback event example
```json
{
"type": "response",
"actor_id": "prime",
"conversation_id": "conv-uuid",
"correlation_id": "corr-uuid",
"content": { "text": "Prime response" }
}
```
---
## State schema (v1 explicit)
Minimum sqlite tables:
- `conversations(id, created_at, updated_at, status, topic_hint)`
- `surface_bindings(surface, channel, thread_id, conversation_id, updated_at)`
- `message_map(surface, source_message_id, bridge_message_id, conversation_id, dedupe_key, created_at)`
- `handoff_state(conversation_id, actor_id, last_handoff_at, last_summary_hash, msg_count_since_handoff)`
- `relay_events(id, correlation_id, source_actor, target_actor, result, created_at)`
- `retry_queue(id, envelope_json, attempt_count, next_attempt_at, last_error)`
- `dead_letter(id, envelope_json, failure_reason, failed_at)`
---
## Reliability and safety
- Exponential backoff retries: 1,2,4,8,... max 60s
- Max attempts: 8 then DLQ
- Signed auth bridge<->adapter (shared secret/JWT)
- No raw secrets in payloads/logs
- Audit log required for all relays
---
## Observability
Metrics:
- `messages_in_total`
- `messages_routed_total{target}`
- `adapter_errors_total{target,code}`
- `handoff_bootstraps_total`
- `dedupe_drops_total`
- `loop_guard_drops_total`
- `relay_cooldown_drops_total`
- `end_to_end_latency_ms`
Endpoints:
- `/healthz`
- `/readyz`
- `/metrics`
---
## MVP acceptance criteria
1. Unmentioned `#general` message fans out to both targets.
2. Explicit mention routes only to named target.
3. Unmentioned fanout allows 0/1/2 valid responses.
4. First cross-surface route includes handoff packet.
5. conversation_id is reused correctly via reply/thread mapping.
6. fork rules create new conversation_id when explicitly requested.
7. Duplicate dedupe key is dropped.
8. Loop controls prevent runaway ping-pong.
---
## Forward path
- v2: conversation registry with stronger ownership/surface mappings
- v3: canonical shared conversation graph/state outside transports