# Implementation Plan: Phase 3B — Basic Single-Timeline Sync with Identity (Integrated)

This document outlines the implementation plan for Phase 3B of identity integration, focusing on integrating the cryptographic session identity into the WebSocket sync peer architecture, and wiring up the Row 3B dev-tools test buttons.

## 1. Goal
The goal of Phase 3B is to achieve successful end-to-end synchronization of a test ibgib `X` over a stateful WebSocket connection using asymmetric session identity validation. 
At the end of the sync saga:
- Both sender and receiver durable spaces must contain the same evolved Domain Keystone (I1).
- Both spaces must contain the full session identity keystone (S) graph evolved to the correct turn count ($n = 3$, or potentially $n = 4$ depending on exact commit phase timeline evolution).
- Both spaces must contain the identical target ibgib `X` dependency graph.

---

## 2. Technical Challenge: Asymmetric Authentication in WebSocket Peers
In V1, only the sender (Alice) signs the synchronization context. The receiver (Bob) skips signing the response context (`skipSign: true`), relying on transport-level security (TLS) for the return path. 
Consequently:
- Alice's request context contains a `signedSessionIdentity`.
- Bob's response context has `signedSessionIdentity` set to `undefined`.

### Current Issue in `SyncPeerWebSocketSender_V1`
In `SyncPeerWebSocketSender_V1.handleRuntimeMessage`, the sender currently attempts to authenticate Bob's response context:
```typescript
if (msg.type === SyncWebSocketMsgType.sync_frame_response) {
    const responseContext = msg.context as SyncSagaContextIbGib_V1;

    // Validate and authenticate Bob's response context first
    await this.authenticateAndValidate({ context: responseContext });
```
Because `authenticateAndValidate` calls `authenticateContextIntrinsically` which expects a signature when `sagaFrame.data.sessionIdentityTjpAddr` is present, this call will throw an error since Bob's response context has no `signedSessionIdentity`.

### Solution
Change `SyncPeerWebSocketSender_V1.handleRuntimeMessage` to run structural/intrinsic validation instead of full authentication on the response context:
```typescript
// Ensure the response context and saga frame are valid structurally
const validationErrors = await validateContextAndSagaFrame({ context: responseContext });
if (validationErrors.length > 0) {
    throw new Error(`Invalid response context received. Errors: ${validationErrors.join(', ')}`);
}
```
The client-side `SyncSagaCoordinator` will then run the turn-by-turn continuation, sequence, and identity validation checks via `validateReturnContext(...)`. This provides a robust stopgap validation for V1 before the receiver-side signing is fully implemented in future versions.


---

## 3. UI Integration: Dev Tools Row 3B
We will wire up the three buttons in `apps/space-gib/src/client/dev-tools.mts` under the `init3bPlaceholder` placeholder handler:

### 3.1. `btn-3b-setup`
- **Actions**:
  1. Generates a new long-lived Domain Keystone (I) for Alice using master secret `'test-sender-secret-phase3'` and unique salts (`'senderidentitysyncsaltphase3'`, `'senderidentitymanagesaltphase3'`).
  2. Registers the genesis Domain Keystone (I) on the server via `apiBridge.postGenesisKeystone(domainI)`.
  3. Creates a local dummy Target IbGib (X) with distinct test data: `{ hello: 'world3', random: Math.random() }`.
  4. Stores `domainI`, `domainIMasterSecret`, and `targetX` in `debugState`.
  5. Updates button text to `✓ 3B Setup Complete` and enables `btn-3b-sync`.

### 3.2. `btn-3b-sync`
- **Actions**:
  1. Instantiates `SyncPeerWebSocketSender_V1` targeting the server's WS and evolution endpoints.
  2. Initializes peer options with Alice's identity, secret, and a newly generated `sagaId`.
  3. Instantiates `SyncSagaCoordinator`.
  4. Calls `coordinator.sync(...)` to synchronize Target X to the server.
  5. Awaits completion (`await syncSaga.done`). This must run without errors.
  6. Updates button text to `✓ 3B Sync Run` and enables `btn-3b-check`.

### 3.3. `btn-3b-check`
- **Actions**:
  1. Resolves the client's latest Target X address and fetches its local dependency graph.
  2. Resolves the server's latest Target X address and fetches its server-side dependency graph using a new API bridge helper.
  3. Asserts the client and server Target X graphs are equivalent:
     - The latest address of X is identical.
     - Graph node counts are identical.
     - All keys and values match.
  4. Resolves the latest session identity (S) address and asserts it evolved to `n = 2` (Init at $n=0$, Connect Handshake at $n=1$, Sync Context Sign at $n=2$).
  5. Verifies the latest S address and graph are identical on both client and server.
  6. Verifies the evolved Domain Keystone (I1) is present in both client and server spaces.
  7. If all checks pass, logs `🎉 ALL PHASE 3B CHECKS PASSED FLAWLESSLY! ✓` and updates button text to `✓ 3B All Passed`.

---

## 4. Concrete Checklist

### [ ] API Bridge Extension
- [ ] Add `getIbGibGraph(domainAddr, ibGibAddr)` to `SpaceGibApiBridge` (`apps/space-gib/src/client/api/space-gib-api-bridge.mts`) to retrieve dependency graphs with `getGraph=true`.

### [ ] WebSocket Peer Adjustments
- [ ] Modify `SyncPeerWebSocketSender_V1.handleRuntimeMessage` to bypass `authenticateAndValidate` on Bob's response context, using `validateContextAndSagaFrame` instead.

### [ ] Dev Tools UI (Row 3B) Wiring
- [ ] Implement `init3bSetupButton` inside `dev-tools.mts`.
- [ ] Implement `init3bSyncButton` inside `dev-tools.mts`.
- [ ] Implement `init3bCheckButton` inside `dev-tools.mts`.
- [ ] Update `initDevTools` to initialize the new button handlers and remove `init3bPlaceholder`.
