I am removing ALL identity/session/identities/keystone-related code from sync
and starting over, now that I have a clearer idea of the requirements.

This is code that I thought would be reusable with minimal adjustments later.

TODO: I have mangled some of the hits for these terms by adding a space after
the first letter. After i am done, need to go back through and search for "k
eystone", "i dentity" "s ession" for these mangled terms.

```typescript
import { KeystoneIbGib_V1, } from "../keystone/keystone-types.mjs";
import { KeystoneService_V1 } from '../../keystone/keystone-service-v1.mjs';
import { validateKeystoneGraph, validateKeystoneTransition } from '../../keystone/keystone-helpers.mjs';

/**
 * creates a session identity keystone based off of the given args.
 *
 * Then, if the {@link primaryIdentity} keystone is provided, this also
 * **signs** this keystone pointing to the address of the sess
 */
public async createSessionIdentity({
    sagaId,
    primaryIdentity,
    nonSessionSecret,
    metaspace,
    localSpace,
}: {
    /**
     * unique to any one particular saga.
     */
    sagaId: string,
    /**
     * optional main identity, e.g., Alice's keystone
     */
    primaryIdentity: KeystoneIbGib_V1 | undefined,
    /**
     * driving secret behind the sync operation. usually, this will be the
     * secret corresponding to a primary identity keystone. But this can
     * also just be a one-time secret just to have more security in the
     * transmission intrinsically.
     */
    nonSessionSecret: string,
    metaspace: MetaspaceService,
    localSpace: IbGibSpaceAny,
}): Promise<{
    sessionIdentity: KeystoneIbGib_V1,
    sessionSecret: string,
    /**
     * if truthy, this evolved from the incoming {@link primaryIdentity} and
     * has already persisted/registered in the incoming {@link localSpace}.
     */
    newPrimaryIdentity: KeystoneIbGib_V1 | undefined
}> {
    const lc = `${this.lc}[${this.createSessionIdentity.name}]`;
    try {
        if (logalot) { console.log(`${lc} starting... (I: 428392a4ee636b7bd8f7d5d89a87e826)`); }

        if (!nonSessionSecret) { throw new Error(`(UNEXPECTED) nonSessionSecret falsy? This is expected to be truthy by this point. (E: 8ce053fe59825a6678713128953b9d26)`); }

        debugger; // step through create session id
        const sessionSecret = await this.deriveSessionSecret({
            sagaId, nonSessionSecret
        });

        // Generate keystone with two initial pools in two steps.
        //   1. Create primary pool with genesis method to correspond to the
        //      sender/sender's secret/identity.
        //   2. Create a separate pool and add separately because a
        //      different pw + config is used for the transition pool.

        if (!this.sessionKeystonePoolConfig) { throw new Error(`this.sessionKeystonePoolConfig falsy. createSessionIdentity requires the coordinator to have this config set. (E: d65bb868d5e3e72c585d64d594e2b826)`); }
        const sessionIdentity_genesis = await this.keystoneSvc.genesis({
            masterSecret: sessionSecret,
            configs: [this.sessionKeystonePoolConfig],
            metaspace,
            space: localSpace,
        });

        // #region sanity validation of genesis keystone
        /**
         * not necessary but since it's a new design, I'm putting in this
         * immediate validation just to put it through its paces. (worth the
         * slight perf hit).
         */
        const validationErrors = await validateGenesisKeystone({
            keystoneIbGib: sessionIdentity_genesis
        });
        if (validationErrors && validationErrors.length > 0) { throw new Error(`(UNEXPECTED) the sessionIdentity_genesis that we just created already has validation errors just after creation? errors: ${validationErrors} (E: e9ca08cf0f8858bb1ace8b9fa89f8726)`); }
        // #endregion sanity validation of genesis keystone

        let newPrimaryIdentity: KeystoneIbGib_V1 | undefined = undefined;
        if (primaryIdentity) {
            newPrimaryIdentity = await this.keystoneSvc.sign({
                latestKeystone: primaryIdentity,
                poolId: this.sessionKeystonePoolConfig.id,
                claim: {
                    verb: KEYSTONE_VERB_SIGN,
                    target: getIbGibAddr({ ibGib: sessionIdentity_genesis }),
                },
                masterSecret: nonSessionSecret,
                metaspace,
                space: localSpace,
                // frameDetails: undefined, // anything to put here?
                // requiredChallengeIds: undefined, // not relevant I think
            });
        }

        // --- IMMEDIATE PERSISTENCE (Audit Trail Rule) ---
        // The initial session keystone is trusted locally and must be stored
        // in the durable space immediately so the FSM and validation steps
        // can use it to sign outgoing contexts.
        const identityIbGibs: IbGib_V1[] = [
            sessionIdentity_genesis
        ];
        if (newPrimaryIdentity) {
            identityIbGibs.push(newPrimaryIdentity);
        }

        // identity ibgibs are single framed without dna, so we only have to
        // worry about each individual frame (i.e. no dependency graph)
        await metaspace.put({
            ibGibs: identityIbGibs,
            space: localSpace,
        });
        for (const identityIbGib of identityIbGibs) {
            await registerNewIbGib({
                ibGib: identityIbGib,
                space: localSpace,
                fnBroadcast: undefined,
            });
        }
        // ------------------------------------------------

        return {
            sessionIdentity: sessionIdentity_genesis,
            sessionSecret,
            newPrimaryIdentity,
        }
    } catch (error) {
        console.error(`${lc} ${extractErrorMsg(error)}`);
        throw error;
    } finally {
        if (logalot) { console.log(`${lc} complete.`); }
    }
}

/**
    * helper that KDFs the given identitySecret, using {@link sagaId} to do so.
    *
    * @returns deterministically derived session secret
    */
private async deriveSessionSecret({
    sagaId,
    nonSessionSecret,
}: {
    sagaId: string,
    /**
        * driving secret behind the sync operation. usually, this will be the
        * secret corresponding to a primary identity keystone. But this can
        * also just be a one-time secret just to have more security in the
        * transmission intrinsically.
        */
    nonSessionSecret: string,
}): Promise<string> {
    const lc = `${this.lc}[${this.deriveSessionSecret.name}]`;
    try {
        if (logalot) { console.log(`${lc} starting... (I: 0de03f8dcd3e32f1fca244e8f2a8a826)`); }

        // Derive session-specific secret using KDF
        const sessionSecret = await deriveKey({
            masterSecret: nonSessionSecret,
            kdfOpts: {
                strategy: KdfStrategy.recursive_salt_wrap,
                salt: sagaId,
                rounds: 10000,
                algorithm: 'SHA-256'
            }
        });

        return sessionSecret;
    } catch (error) {
        console.error(`${lc} ${extractErrorMsg(error)}`);
        throw error;
    } finally {
        if (logalot) { console.log(`${lc} complete.`); }
    }
}



/**
 * move to sync-peer-helpers.mts as a pure function?
 */
export async function authenticateContext({
    context,
    space,
    keystoneSvc,
}: {
    context: SyncSagaContextIbGib_V1,
    space: IbGibSpaceAny,
    keystoneSvc?: KeystoneService_V1,
}): Promise<string[]> {
    const lc = `[${authenticateContext.name}]`;
    try {
        if (logalot) { console.log(`${lc} starting... (I: 2677a482dfa873dcd1aa04a3031ff826)`); }

        const errors: string[] = [];
        if (!keystoneSvc) {
            if (logalot) { console.warn(`${lc} No keystoneSvc provided. Skipping context authentication. (W: d34b8ad93d84a1ba8d8f7facd288826)`); }
            return errors;
        }

        // Bill Architecture: We only sign at the context level.
        // If the context refers to a session keystone, we must have a signedSessionKeystone
        // as well to verify the most recent turn.
        const { sessionKeystone: prevKeystoneAddrs } = context.rel8ns || {};
        const { signedSessionKeystone: currKeystone } = context;

        if (prevKeystoneAddrs && prevKeystoneAddrs.length > 0) {
            if (!currKeystone) {
                errors.push(`context.rel8ns.sessionKeystone present but context.signedSessionKeystone falsy. (E: b6e5a8ad93d84260a8d8e7facd288826)`);
                return errors;
            }

            // Retrieve the previous keystone frame from space
            const prevKeystoneAddr = prevKeystoneAddrs[0];
            const getPrevRes = await getFromSpace({ addr: prevKeystoneAddr, space });
            if (!getPrevRes.success || !getPrevRes.ibGibs || getPrevRes.ibGibs.length === 0) {
                errors.push(`couldn't find previous session keystone (${prevKeystoneAddr}) in space (${space.ib}). (E: 7c34b8ad94d84a9ba8cbe7facd288826)`);
                return errors;
            }
            const prevKeystone = getPrevRes.ibGibs[0] as KeystoneIbGib_V1;

            // 1. Validate the transition (API replay of evolution + intrinsic validation)
            const transitionErrors = await keystoneSvc.validate({
                currentIbGib: currKeystone,
                prevIbGib: prevKeystone,
            });
            if (transitionErrors.length > 0) {
                errors.push(`Invalid session keystone transition: ${transitionErrors.join(', ')} (E: d34b8ad95d84b90a8d8ef7facd288826)`);
            }

            // 2. Verify that the signature in current keystone actually targets this context
            const contextAddr = getIbGibAddr({ ibGib: context });
            const proofTargetsThisContext = currKeystone.data?.proofs.some(p => p.claim.target === contextAddr);
            if (!proofTargetsThisContext) {
                errors.push(`Session keystone signature does not target the current context ibgib (${contextAddr}). (E: f3e5a8ad96d84c1ba8d8f7facd288826)`);
            }
        }

        return errors;
    } catch (error) {
        console.error(`${lc} ${extractErrorMsg(error)}`);
        throw error;
    } finally {
        if (logalot) { console.log(`${lc} complete.`); }
    }
}



// #region this sync peer innerspace sendContextRequest

            // Bill architecture: Keystone identity transportation.
            // On each turn, the sender must include the current signed session
            // keystone. If it's the first turn (Init), we include the entire
            // keystone graph to ensure the receiver has the primary-to-session
            // authorized link.
            const identityIbGibs: IbGib_V1[] = [];
            const { signedSessionKeystone } = context;
            if (signedSessionKeystone) {
                if (msg.data.stage === SyncStage.init) {
                    // transmit full keystone graph on the first connect handshake
                    const keystoneGraph = await getDependencyGraph({
                        ibGib: signedSessionKeystone,
                        space: localSpace,
                    });
                    identityIbGibs.push(...Object.values(keystoneGraph));
                } else {
                    // transmit only the latest evolution for subsequent turns
                    identityIbGibs.push(signedSessionKeystone);
                }
            }

// #endregion this sync peer innerspace sendContextRequest


// #region SyncSagaContextRel8ns_V1

    /**
     * The Ephemeral Session Keystone Identity used for this saga. Required for
     * validating the saga frame and this context.
     *
     * WARNING!!!: THIS DOES NOT POINT TO THE CURRENT SESSION KEYSTONE IN
     * {@link SyncSagaContextIbGib_V1.signedSessionKeystone}. This points to the
     * PREVIOUS FRAME (immediate past) of that frame. That session keystone
     * signs with THIS context's frame as its target, so it is logically
     * impossible because the hash would be different.
     *
     * ## notes
     *
     * ATOW (02/18/2026), this is a single address that will have a primary pool
     * for the sender and a delegated pool for the receiver.
     *
     * @see {@link SyncSagaContextIbGib_V1.signedSessionKeystone}
     */
    sessionKeystone?: IbGibAddr[];

// #endregion SyncSagaContextRel8ns_V1

```