Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
8.3 KB
Raw Blame
/**
 * Guest sources (GBRA-504): the reads and writes behind `gbrain guests init` and
 * `gbrain sources writers`. guest_sources is the authority the trust trigger
 * reads (guests/schema.ts); sources.config carries `guest: true` and
 * `trust_ceiling` for people and `gbrain sources list`, and `federated: true`
 * so owner reads that widen to federated sources include it.
 */
import type { BrainEngine } from '../engine.ts';
import { opError, type OperationError } from '../ops/contract.ts';
import type { Principal } from '../persistence/model.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
import { addSource } from '../sources-ops.ts';
import type { TrustTier } from '../trust/tier.ts';
import { lookupGuestSource } from './admission.ts';

export const GUEST_TRUST_CEILING: TrustTier = 'external_untrusted';
const PRINCIPAL_KINDS: readonly Principal['kind'][] = ['oauth_client', 'legacy_token', 'local_cli', 'local_stdio', 'application'];
/** How a writer is named: the persistence attribution principal, `<kind>:<id>`. */
export const GUEST_WRITER_FORMAT = `<${PRINCIPAL_KINDS.join('|')}>:<id>`;

/** True when `value` names a principal the way the trust trigger compares it. */
export function isGuestWriter(value: string): boolean {
  const at = value.indexOf(':');
  return at > 0 && (PRINCIPAL_KINDS as readonly string[]).includes(value.slice(0, at)) && /^[\x21-\x7e]{1,200}$/.test(value.slice(at + 1));
}

/**
 * The oauth_client writers in `writers` that name no live registered OAuth client, refused as client_not_found with
 * nothing written: a mistyped or deleted client id would sit on the list and let nobody write.
 */
export async function unregisteredClientWriters(engine: Pick<BrainEngine, 'executeRaw'>, writers: readonly string[]): Promise<OperationError | null> {
  const clientId = (w: string) => w.startsWith('oauth_client:') ? w.slice('oauth_client:'.length) : null;
  const ids = writers.map(clientId).filter((id): id is string => id !== null);
  if (!ids.length) return null;
  const live = new Set((await engine.executeRaw<{ client_id: string }>(
    'SELECT client_id FROM oauth_clients WHERE client_id = ANY($1::text[]) AND deleted_at IS NULL', [ids])).map(r => r.client_id));
  const unknown = writers.filter(w => { const id = clientId(w); return id !== null && !live.has(id); });
  if (!unknown.length) return null;
  return opError('client_not_found', `No registered OAuth client matches writer ${unknown.join(', ')}; nothing was written.`,
    'List the clients with gbrain auth clients --json and name each writer as oauth_client:<client id> from that list (register the broker first with gbrain auth register-client).',
    { fix: { argv: ['gbrain', 'auth', 'clients', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists the OAuth clients registered on this brain.' } });
}

export interface GuestSource { source_id: string; writers: string[]; trust_ceiling: string }

export const readGuestSource = (engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<GuestSource | null> => lookupGuestSource(engine, sourceId);

export interface GuestSourcePlan { sourceId: string; exists: boolean; localPath: string | null; guest: GuestSource | null; writers: string[];
  /** Its config already says guest: true, so its pages read as guest notes and init repairs it whatever it holds. */
  configGuest: boolean;
  /** Pages in an existing source neither guest record marks yet (deleted ones not yet purged included); 0 otherwise. */
  pages: number }

/** What `guests init` would do, read without writing. `writers` is the list after the run (existing ones kept). */
export async function planGuestSource(engine: BrainEngine, sourceId: string, writers: readonly string[]): Promise<GuestSourcePlan> {
  const [source] = await engine.executeRaw<{ local_path: string | null; config_guest: boolean }>(
    "SELECT local_path, COALESCE(config->>'guest' = 'true', false) AS config_guest FROM sources WHERE id = $1", [sourceId]);
  const guest = source ? await readGuestSource(engine, sourceId) : null;
  const unmarked = !!source && !guest && !source.config_guest;
  const [held] = unmarked ? await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id = $1', [sourceId]) : [];
  return { sourceId, exists: !!source, localPath: source?.local_path ?? null, guest, writers: [...new Set([...(guest?.writers ?? []), ...writers])].sort(),
    configGuest: source?.config_guest === true, pages: Number(held?.n ?? 0) };
}

/** initGuestSource refused: the source is not yet a guest source and already holds pages (deleted ones not yet purged included). */
export class GuestSourceHoldsPages extends Error {
  constructor(readonly sourceId: string, readonly pages: number) {
    super(`Source "${sourceId}" already holds ${pages} page(s), counting deleted pages not yet purged (a restore would bring them back). Every page in a guest source reads as an outside guest's words and only listed writers can change it, so gbrain will not make this one a guest source. Pick another name with --source.`);
  }
}

/**
 * Makes `sourceId` a guest source: creates it database-only and federated when
 * missing, sets its guest config and writes its guest_sources row, in one
 * transaction (a managed brain creates the source through its lifecycle first).
 * Reads find guest sources from these two records (guests/marker.ts guestSourceSql).
 * The database refuses a source with a local_path (guest_source_database_only). An existing source that neither guest
 * record marks yet must hold no page: counted under the source row's lock, which a page insert's key check waits on, so
 * no page lands between the count and the commit (GuestSourceHoldsPages). A source one record already marks (its config
 * says guest, or guest_sources lists it) is repaired whatever it holds: its pages already read as guest notes.
 */
export async function initGuestSource(engine: BrainEngine, sourceId: string, writers: readonly string[]): Promise<GuestSource> {
  const managed = await managedPersistenceEnabled(engine);
  if (managed && !(await planGuestSource(engine, sourceId, [])).exists) await addSource(engine, { id: sourceId, federated: true });
  return engine.transaction(async tx => {
    const [source] = await tx.executeRaw<{ id: string; guest: boolean }>(`SELECT s.id, (COALESCE(s.config->>'guest' = 'true', false)
      OR EXISTS (SELECT 1 FROM guest_sources g WHERE g.source_id = s.id)) AS guest FROM sources s WHERE s.id = $1 FOR UPDATE OF s`, [sourceId]);
    if (!source) await addSource(tx, { id: sourceId, federated: true });
    else if (!source.guest) {
      const [held] = await tx.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id = $1', [sourceId]);
      if (Number(held?.n ?? 0) > 0) throw new GuestSourceHoldsPages(sourceId, Number(held!.n));
    }
    await tx.executeRaw(`UPDATE sources SET config = config || jsonb_build_object('federated', true, 'guest', true, 'trust_ceiling', $2::text) WHERE id = $1`,
      [sourceId, GUEST_TRUST_CEILING]);
    const [row] = await tx.executeRaw<GuestSource>(`INSERT INTO guest_sources (source_id, writers, trust_ceiling) VALUES ($1, $2::text[], $3)
      ON CONFLICT (source_id) DO UPDATE SET writers = ARRAY(SELECT DISTINCT w FROM unnest(guest_sources.writers || EXCLUDED.writers) AS w ORDER BY w)
      RETURNING source_id, writers, trust_ceiling`, [sourceId, [...new Set(writers)].sort(), GUEST_TRUST_CEILING]);
    return row!;
  });
}

export type WritersChange = { clear?: boolean; add?: readonly string[]; remove?: readonly string[] };

/** Applies a writer-list change (clear first, then removals, then additions); null when the source is not a guest source. */
export async function changeGuestWriters(engine: BrainEngine, sourceId: string, change: WritersChange): Promise<GuestSource | null> {
  return engine.transaction(async tx => {
    const [row] = await tx.executeRaw<GuestSource>('SELECT source_id, writers, trust_ceiling FROM guest_sources WHERE source_id = $1 FOR UPDATE', [sourceId]);
    if (!row) return null;
    const removed = new Set(change.remove ?? []);
    const writers = [...new Set([...(change.clear ? [] : row.writers.filter(w => !removed.has(w))), ...(change.add ?? [])])].sort();
    const [updated] = await tx.executeRaw<GuestSource>('UPDATE guest_sources SET writers = $2::text[] WHERE source_id = $1 RETURNING source_id, writers, trust_ceiling',
      [sourceId, writers]);
    return updated!;
  });
}