← back to PrimeLocus__bmo

Function bodies 413 total

All specs Real LLM only Function bodies
makeThoughtRequest function · typescript · L149-L153 (5 LOC)
beau-terminal/src/lib/server/brain/types.ts
export function makeThoughtRequest(
  input: ThoughtInput,
  hints?: BrainHints,
  parentRequestId?: string,
): Extract<BrainRequestV1, { kind: 'thought.generate' }> {
makeManualRequest function · typescript · L165-L168 (4 LOC)
beau-terminal/src/lib/server/brain/types.ts
export function makeManualRequest(
  input: { text: string; label?: string },
  hints?: BrainHints,
): Extract<BrainRequestV1, { kind: 'manual.prompt' }> {
makeBrainRequest function · typescript · L183-L188 (6 LOC)
beau-terminal/src/lib/server/brain/types.ts
export function makeBrainRequest(
  kind: 'thought.generate',
  input: ThoughtInput,
  hints?: BrainHints,
  parentRequestId?: string,
): Extract<BrainRequestV1, { kind: 'thought.generate' }>;
makeBrainRequest function · typescript · L189-L194 (6 LOC)
beau-terminal/src/lib/server/brain/types.ts
export function makeBrainRequest(
  kind: 'manual.prompt',
  input: { text: string; label?: string },
  hints?: BrainHints,
  parentRequestId?: string,
): Extract<BrainRequestV1, { kind: 'manual.prompt' }>;
makeBrainRequest function · typescript · L195-L205 (11 LOC)
beau-terminal/src/lib/server/brain/types.ts
export function makeBrainRequest(
  kind: BrainRequestV1['kind'],
  input: ThoughtInput | { text: string; label?: string },
  hints?: BrainHints,
  parentRequestId?: string,
): BrainRequestV1 {
  if (kind === 'thought.generate') {
    return makeThoughtRequest(input as ThoughtInput, hints, parentRequestId);
  }
  return makeManualRequest(input as { text: string; label?: string }, hints);
}
formatDebriefPrompt function · typescript · L10-L19 (10 LOC)
beau-terminal/src/lib/server/creative/debrief.ts
export function formatDebriefPrompt(input: DebriefInput): string {
  const venueStr = input.venue ? ` at ${input.venue}` : '';
  const clipList = input.clips.join(', ');
  return [
    `Reflect on a ${input.durationMinutes}-minute VJ session${venueStr}.`,
    `BPM ranged from ${input.bpmRange[0]} to ${input.bpmRange[1]}.`,
    `Clips used: ${clipList}.`,
    `Write a brief, poetic debrief — what Beau noticed about the visual flow, energy shifts, and moments of emergence.`,
  ].join(' ');
}
DebriefScheduler class · typescript · L26-L59 (34 LOC)
beau-terminal/src/lib/server/creative/debrief.ts
export class DebriefScheduler {
  private _pending = new Map<number, ReturnType<typeof setTimeout>>();
  private _delayMs: number;
  private _onDebrief: (sessionId: number) => void;

  constructor(config: DebriefSchedulerConfig) {
    this._delayMs = config.delayMs ?? 3 * 60 * 1000;
    this._onDebrief = config.onDebrief;
  }

  scheduleDebrief(sessionId: number): void {
    this.cancel(sessionId);
    const timer = setTimeout(() => {
      this._pending.delete(sessionId);
      this._onDebrief(sessionId);
    }, this._delayMs);
    this._pending.set(sessionId, timer);
  }

  cancel(sessionId: number): void {
    const timer = this._pending.get(sessionId);
    if (timer) {
      clearTimeout(timer);
      this._pending.delete(sessionId);
    }
  }

  cleanup(): void {
    for (const timer of this._pending.values()) {
      clearTimeout(timer);
    }
    this._pending.clear();
  }
}
Repobility — the code-quality scanner for AI-generated software · https://repobility.com
constructor method · typescript · L31-L34 (4 LOC)
beau-terminal/src/lib/server/creative/debrief.ts
  constructor(config: DebriefSchedulerConfig) {
    this._delayMs = config.delayMs ?? 3 * 60 * 1000;
    this._onDebrief = config.onDebrief;
  }
scheduleDebrief method · typescript · L36-L43 (8 LOC)
beau-terminal/src/lib/server/creative/debrief.ts
  scheduleDebrief(sessionId: number): void {
    this.cancel(sessionId);
    const timer = setTimeout(() => {
      this._pending.delete(sessionId);
      this._onDebrief(sessionId);
    }, this._delayMs);
    this._pending.set(sessionId, timer);
  }
cancel method · typescript · L45-L51 (7 LOC)
beau-terminal/src/lib/server/creative/debrief.ts
  cancel(sessionId: number): void {
    const timer = this._pending.get(sessionId);
    if (timer) {
      clearTimeout(timer);
      this._pending.delete(sessionId);
    }
  }
cleanup method · typescript · L53-L58 (6 LOC)
beau-terminal/src/lib/server/creative/debrief.ts
  cleanup(): void {
    for (const timer of this._pending.values()) {
      clearTimeout(timer);
    }
    this._pending.clear();
  }
validateImageMime function · typescript · L12-L14 (3 LOC)
beau-terminal/src/lib/server/creative/photography.ts
export function validateImageMime(mimeType: string): boolean {
  return (ALLOWED_IMAGE_TYPES as readonly string[]).includes(mimeType);
}
generatePhotoFilename function · typescript · L16-L19 (4 LOC)
beau-terminal/src/lib/server/creative/photography.ts
export function generatePhotoFilename(originalName: string): string {
  const ext = originalName.includes('.') ? originalName.split('.').pop()! : 'jpg';
  return `${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
}
ResolumeSessionManager class · typescript · L27-L103 (77 LOC)
beau-terminal/src/lib/server/creative/resolume.ts
export class ResolumeSessionManager {
  private _activeSessionId: number | null = null;
  private _silenceTimer: ReturnType<typeof setTimeout> | null = null;
  private _silenceThresholdMs: number;
  private _onSessionStart: (sessionId: number) => void;
  private _onSessionEnd: (sessionId: number) => void;
  private _stats: SessionStats | null = null;

  constructor(config: ResolumeSessionConfig = {}) {
    this._silenceThresholdMs = config.silenceThresholdMs ?? 10 * 60 * 1000;
    this._onSessionStart = config.onSessionStart ?? (() => {});
    this._onSessionEnd = config.onSessionEnd ?? (() => {});
  }

  get activeSessionId(): number | null {
    return this._activeSessionId;
  }

  get isActive(): boolean {
    return this._activeSessionId !== null;
  }

  onLiveEvent(event: LiveEvent): void {
    if (!this._activeSessionId) {
      this._activeSessionId = nextId++;
      this._stats = {
        bpmMin: event.bpm,
        bpmMax: event.bpm,
        bpmSum: event.bpm,
        eventCou
constructor method · typescript · L35-L39 (5 LOC)
beau-terminal/src/lib/server/creative/resolume.ts
  constructor(config: ResolumeSessionConfig = {}) {
    this._silenceThresholdMs = config.silenceThresholdMs ?? 10 * 60 * 1000;
    this._onSessionStart = config.onSessionStart ?? (() => {});
    this._onSessionEnd = config.onSessionEnd ?? (() => {});
  }
Repobility · code-quality intelligence platform · https://repobility.com
onLiveEvent method · typescript · L49-L70 (22 LOC)
beau-terminal/src/lib/server/creative/resolume.ts
  onLiveEvent(event: LiveEvent): void {
    if (!this._activeSessionId) {
      this._activeSessionId = nextId++;
      this._stats = {
        bpmMin: event.bpm,
        bpmMax: event.bpm,
        bpmSum: event.bpm,
        eventCount: 1,
        clips: [event.clip],
      };
      this._onSessionStart(this._activeSessionId);
    } else if (this._stats) {
      this._stats.bpmMin = Math.min(this._stats.bpmMin, event.bpm);
      this._stats.bpmMax = Math.max(this._stats.bpmMax, event.bpm);
      this._stats.bpmSum += event.bpm;
      this._stats.eventCount++;
      if (!this._stats.clips.includes(event.clip)) {
        this._stats.clips.push(event.clip);
      }
    }
    this._resetSilenceTimer();
  }
getSessionStats method · typescript · L72-L74 (3 LOC)
beau-terminal/src/lib/server/creative/resolume.ts
  getSessionStats(): SessionStats | null {
    return this._stats ? { ...this._stats, clips: [...this._stats.clips] } : null;
  }
cleanup method · typescript · L76-L87 (12 LOC)
beau-terminal/src/lib/server/creative/resolume.ts
  cleanup(): void {
    if (this._silenceTimer) {
      clearTimeout(this._silenceTimer);
      this._silenceTimer = null;
    }
    if (this._activeSessionId) {
      const id = this._activeSessionId;
      this._activeSessionId = null;
      this._stats = null;
      this._onSessionEnd(id);
    }
  }
_resetSilenceTimer method · typescript · L89-L102 (14 LOC)
beau-terminal/src/lib/server/creative/resolume.ts
  private _resetSilenceTimer(): void {
    if (this._silenceTimer) {
      clearTimeout(this._silenceTimer);
    }
    this._silenceTimer = setTimeout(() => {
      if (this._activeSessionId) {
        const id = this._activeSessionId;
        this._activeSessionId = null;
        this._stats = null;
        this._onSessionEnd(id);
      }
      this._silenceTimer = null;
    }, this._silenceThresholdMs);
  }
parseResolumeLiveMessage function · typescript · L115-L128 (14 LOC)
beau-terminal/src/lib/server/creative/resolume.ts
export function parseResolumeLiveMessage(msg: string): LiveEvent | null {
  try {
    const data = JSON.parse(msg);
    if (typeof data.clip !== 'string') return null;
    return {
      clip: data.clip,
      bpm: typeof data.bpm === 'number' ? data.bpm : 0,
      layer: typeof data.layer === 'number' ? data.layer : undefined,
      intensity: typeof data.intensity === 'number' ? data.intensity : undefined,
    };
  } catch {
    return null;
  }
}
WitnessController class · typescript · L8-L45 (38 LOC)
beau-terminal/src/lib/server/creative/witness.ts
export class WitnessController {
  private _isWitnessing = false;
  private _previousMode: string | null = null;
  private _onModeChange: (mode: string) => void;

  constructor(config: WitnessConfig) {
    this._onModeChange = config.onModeChange;
  }

  get isWitnessing(): boolean {
    return this._isWitnessing;
  }

  onSessionStart(presenceState: string, currentMode: string): void {
    if (presenceState === 'occupied') {
      this._previousMode = currentMode;
      this._isWitnessing = true;
      this._onModeChange('witness');
    }
  }

  onSessionEnd(): void {
    if (this._isWitnessing && this._previousMode !== null) {
      this._isWitnessing = false;
      this._onModeChange(this._previousMode);
      this._previousMode = null;
    }
  }

  onPresenceChange(presenceState: string, sessionActive: boolean): void {
    if (!sessionActive || this._isWitnessing) return;
    if (presenceState === 'occupied') {
      this._previousMode = this._previousMode ?? 'ambient';
      this.
constructor method · typescript · L13-L15 (3 LOC)
beau-terminal/src/lib/server/creative/witness.ts
  constructor(config: WitnessConfig) {
    this._onModeChange = config.onModeChange;
  }
onSessionStart method · typescript · L21-L27 (7 LOC)
beau-terminal/src/lib/server/creative/witness.ts
  onSessionStart(presenceState: string, currentMode: string): void {
    if (presenceState === 'occupied') {
      this._previousMode = currentMode;
      this._isWitnessing = true;
      this._onModeChange('witness');
    }
  }
Provenance: Repobility (https://repobility.com) — every score reproducible from /scan/
onSessionEnd method · typescript · L29-L35 (7 LOC)
beau-terminal/src/lib/server/creative/witness.ts
  onSessionEnd(): void {
    if (this._isWitnessing && this._previousMode !== null) {
      this._isWitnessing = false;
      this._onModeChange(this._previousMode);
      this._previousMode = null;
    }
  }
onPresenceChange method · typescript · L37-L44 (8 LOC)
beau-terminal/src/lib/server/creative/witness.ts
  onPresenceChange(presenceState: string, sessionActive: boolean): void {
    if (!sessionActive || this._isWitnessing) return;
    if (presenceState === 'occupied') {
      this._previousMode = this._previousMode ?? 'ambient';
      this._isWitnessing = true;
      this._onModeChange('witness');
    }
  }
logActivity function · typescript · L4-L12 (9 LOC)
beau-terminal/src/lib/server/db/activity.ts
export function logActivity(
  entityType: string,
  entityId: string | number | null,
  action: string,
  summary: string
) {
  const id = entityId != null ? String(entityId) : null;
  db.insert(activityLog).values({ entityType, entityId: id, action, summary }).run();
}
reconcileMigrations function · typescript · L35-L66 (32 LOC)
beau-terminal/src/lib/server/db/index.ts
function reconcileMigrations() {
  const migrationsFolder = join(process.cwd(), 'drizzle');
  const journal = JSON.parse(
    readFileSync(join(migrationsFolder, 'meta', '_journal.json'), 'utf8')
  );
  const rows = sqlite.prepare('SELECT hash FROM "__drizzle_migrations"').all() as { hash: string }[];
  const applied = new Set(rows.map((r) => r.hash));
  for (const entry of journal.entries) {
    const sql = readFileSync(join(migrationsFolder, `${entry.tag}.sql`), 'utf8');
    const hash = createHash('sha256').update(sql).digest('hex');
    if (applied.has(hash)) continue;
    const statements = sql.split('--> statement-breakpoint');
    for (const stmt of statements) {
      const trimmed = stmt.trim();
      if (!trimmed) continue;
      try {
        sqlite.prepare(trimmed).run();
      } catch (err: unknown) {
        const sqlErr = err as { code?: string; message?: string };
        if (sqlErr.code === 'SQLITE_ERROR' &&
            (sqlErr.message?.includes('already exists') || sq
shouldAdvancePartStatus function · typescript · L410-L416 (7 LOC)
beau-terminal/src/lib/server/db/seed.ts
function shouldAdvancePartStatus(currentStatus: string, desiredStatus: string) {
  if (currentStatus === desiredStatus) return false;
  if (currentStatus === 'ordered' && (desiredStatus === 'shipped' || desiredStatus === 'delivered' || desiredStatus === 'installed')) return true;
  if (currentStatus === 'shipped' && (desiredStatus === 'delivered' || desiredStatus === 'installed')) return true;
  if (currentStatus === 'delivered' && desiredStatus === 'installed') return true;
  return false;
}
buildPartSyncPatch function · typescript · L418-L444 (27 LOC)
beau-terminal/src/lib/server/db/seed.ts
function buildPartSyncPatch(existing: PartRow, desired: PartSeed): Partial<PartSeed> | null {
  const patch: Partial<PartSeed> = {};

  if (shouldAdvancePartStatus(existing.status, desired.status ?? 'ordered')) {
    patch.status = desired.status;
    patch.eta = desired.eta;
    patch.expectedDelivery = desired.expectedDelivery;
  }

  const wantsDeliveredMarker = desired.expectedDelivery === 'Delivered' &&
    (existing.status === 'delivered' || existing.status === 'installed');
  if (wantsDeliveredMarker) {
    if (!existing.expectedDelivery) patch.expectedDelivery = 'Delivered';
    if (!existing.eta) patch.eta = desired.eta;
  }

  if (existing.status === 'shipped' && desired.status === 'shipped') {
    if (desired.expectedDelivery && !existing.expectedDelivery) {
      patch.expectedDelivery = desired.expectedDelivery;
    }
    if (desired.eta && !existing.eta) {
      patch.eta = desired.eta;
    }
  }

  return Object.keys(patch).length ? patch : null;
}
syncParts function · typescript · L446-L467 (22 LOC)
beau-terminal/src/lib/server/db/seed.ts
function syncParts() {
  const existingParts = new Map(db.select().from(parts).all().map((part) => [part.id, part]));
  let inserted = 0;
  let updated = 0;

  for (const part of PART_SEEDS) {
    const existing = existingParts.get(part.id ?? -1);
    if (!existing) {
      db.insert(parts).values(part).run();
      inserted++;
      continue;
    }

    const patch = buildPartSyncPatch(existing, part);
    if (!patch) continue;

    db.update(parts).set(patch).where(eq(parts.id, existing.id)).run();
    updated++;
  }

  return { inserted, updated };
}
syncSoftware function · typescript · L469-L525 (57 LOC)
beau-terminal/src/lib/server/db/seed.ts
function syncSoftware() {
  const existingPhases = db.select().from(softwarePhases).all();
  const phaseIds = new Map(existingPhases.map((phase) => [phase.phase, phase.id]));
  let insertedPhases = 0;
  let insertedSteps = 0;
  let updatedSteps = 0;

  for (const phase of PHASE_DATA) {
    let phaseId = phaseIds.get(phase.phase);
    if (phaseId === undefined) {
      phaseId = db.insert(softwarePhases)
        .values({ phase: phase.phase, order: phase.order })
        .returning()
        .get().id;
      phaseIds.set(phase.phase, phaseId);
      insertedPhases++;
    }

    const resolvedPhaseId = phaseId;
    for (const step of phase.steps) {
      const seedDone = 'done' in step ? (step as { done: boolean }).done : false;
      const seedReqParts = 'requiredPartIds' in step
        ? JSON.stringify((step as { requiredPartIds: number[] }).requiredPartIds)
        : '[]';
      const existingStep = db.select().from(softwareSteps).where(eq(softwareSteps.id, step.id)).get();
      if 
Repobility · code-quality intelligence · https://repobility.com
syncIdeas function · typescript · L527-L557 (31 LOC)
beau-terminal/src/lib/server/db/seed.ts
function syncIdeas() {
  const existingIdeas = new Map(db.select().from(ideas).all().map((idea) => [idea.id, idea]));
  let inserted = 0;
  let updated = 0;

  for (const idea of IDEA_SEEDS) {
    const existing = existingIdeas.get(idea.id ?? '');
    if (!existing) {
      db.insert(ideas).values(idea).run();
      inserted++;
      continue;
    }

    // Advance done status (true→false never happens)
    const shouldAdvanceDone = idea.done && !existing.done;
    const textOrPriorityChanged = existing.priority !== idea.priority || existing.text !== idea.text;

    if (!textOrPriorityChanged && !shouldAdvanceDone) continue;

    const patch: Record<string, unknown> = { priority: idea.priority, text: idea.text };
    if (shouldAdvanceDone) patch.done = true;

    db.update(ideas)
      .set(patch)
      .where(eq(ideas.id, existing.id))
      .run();
    updated++;
  }

  return { inserted, updated };
}
seed function · typescript · L559-L571 (13 LOC)
beau-terminal/src/lib/server/db/seed.ts
export function seed() {
  const partStats = syncParts();
  const softwareStats = syncSoftware();
  const ideaStats = syncIdeas();
  seedLlmVariants();
  const appliedChanges = partStats.inserted + partStats.updated + softwareStats.insertedPhases +
    softwareStats.insertedSteps + softwareStats.updatedSteps + ideaStats.inserted + ideaStats.updated;

  console.log(
    `[seed] Synced — ${PART_SEEDS.length} parts, ${PHASE_DATA.length} phases, ${TOTAL_STEPS} steps, ${IDEA_SEEDS.length} ideas` +
    (appliedChanges ? ` (${appliedChanges} changes applied)` : '')
  );
}
seedLlmVariants function · typescript · L574-L595 (22 LOC)
beau-terminal/src/lib/server/db/seed.ts
export function seedLlmVariants() {
  const llmVariantSeeds = [
    { displayName: 'Qwen 2.5 1.5B (T1 base)', family: 'qwen2.5', baseModel: 'qwen2.5:1.5b', trainingMethod: 'base', runtime: 'ollama', tier: 't1', status: 'active' },
    { displayName: 'Gemma 3 4B (T2 base)', family: 'gemma3', baseModel: 'gemma3:4b', trainingMethod: 'base', runtime: 'ollama', tier: 't2', status: 'active' },
    { displayName: 'Llama 3.1 8B (T3 base)', family: 'llama3.1', baseModel: 'llama3.1:8b', trainingMethod: 'base', runtime: 'ollama', tier: 't3', status: 'active' },
    { displayName: 'Qwen 3 30B (T4 base)', family: 'qwen3', baseModel: 'qwen3:30b', trainingMethod: 'base', runtime: 'ollama', tier: 't4', status: 'active' },
  ] as const;

  const existing = db.select().from(llmModelVariants).all();
  const existingBaseModels = new Set(existing.map(v => v.baseModel));
  let inserted = 0;

  for (const variant of llmVariantSeeds) {
    if (existingBaseModels.has(variant.baseModel)) continue;
    db.insert
seedIntegrations function · typescript · L597-L618 (22 LOC)
beau-terminal/src/lib/server/db/seed.ts
export function seedIntegrations() {
  const existing = db.select().from(integrations).all();
  if (existing.length > 0) return;

  const seeds = [
    { name: 'MQTT (Mosquitto)', icon: '📡', type: 'mqtt', endpoint: 'mqtt://localhost:1883', healthCheck: 'mqtt-ping', sortOrder: 0 },
    { name: 'Home Assistant', icon: '🏠', type: 'api', endpoint: 'http://homeassistant.local:8123', healthCheck: 'http-get', sortOrder: 1 },
    { name: 'Resolume Arena', icon: '🎛', type: 'osc', endpoint: 'osc://localhost:7000', healthCheck: 'none', sortOrder: 2 },
    { name: 'Tailscale', icon: '🌐', type: 'custom', endpoint: null, healthCheck: 'none', notes: 'Auto-detected via tailscale status', sortOrder: 3 },
    { name: 'Ollama (Pi)', icon: '🧠', type: 'api', endpoint: 'http://localhost:11434', healthCheck: 'http-get', sortOrder: 4 },
    { name: 'Ollama (ThinkStation)', icon: '🧠', type: 'api', endpoint: 'http://thinkstation:11434', healthCheck: 'http-get', sortOrder: 5 },
    { name: 'ChromaDB', icon: '🔍',
seedLinks function · typescript · L620-L637 (18 LOC)
beau-terminal/src/lib/server/db/seed.ts
export function seedLinks() {
  // Check if any steps are missing links — runs once after column is added
  const missing = db.select().from(softwareSteps).all().filter(s => s.links === '[]');
  if (missing.length > 0) {
    for (const [id, links] of Object.entries(STEP_LINKS)) {
      db.update(softwareSteps).set({ links: JSON.stringify(links) }).where(eq(softwareSteps.id, id)).run();
    }
    console.log('[seedLinks] Step links populated');
  }

  const missingIdeas = db.select().from(ideas).all().filter(i => i.links === '[]');
  if (missingIdeas.length > 0) {
    for (const [id, links] of Object.entries(IDEA_LINKS)) {
      db.update(ideas).set({ links: JSON.stringify(links) }).where(eq(ideas.id, id)).run();
    }
    console.log('[seedLinks] Idea links populated');
  }
}
getLuxLabel function · typescript · L10-L15 (6 LOC)
beau-terminal/src/lib/server/environment/lux.ts
export function getLuxLabel(lux: number): LuxLabel {
  for (const [threshold, label] of LUX_THRESHOLDS) {
    if (lux >= threshold) return label;
  }
  return 'dark';
}
PresenceMachine class · typescript · L10-L46 (37 LOC)
beau-terminal/src/lib/server/environment/presence.ts
export class PresenceMachine {
  state: PresenceState = 'uncertain';
  confidence = 0;

  private negativeCount = 0;
  private listeners = new Set<(state: PresenceState) => void>();

  onChange(fn: (state: PresenceState) => void) {
    this.listeners.add(fn);
    return () => this.listeners.delete(fn);
  }

  onCameraEvent(event: CameraEvent) {
    if (event.detected) {
      this.negativeCount = 0;
      this.confidence = event.confidence;
      this.transition('occupied');
    } else {
      this.negativeCount++;
      if (this.negativeCount >= DEBOUNCE_THRESHOLD) {
        this.confidence = event.confidence;
        this.transition('empty');
      }
      // Otherwise stay in current state (debounce)
    }
  }

  getSnapshot() {
    return { state: this.state, confidence: this.confidence };
  }

  private transition(next: PresenceState) {
    if (this.state === next) return;
    this.state = next;
    for (const fn of this.listeners) fn(next);
  }
}
onChange method · typescript · L17-L20 (4 LOC)
beau-terminal/src/lib/server/environment/presence.ts
  onChange(fn: (state: PresenceState) => void) {
    this.listeners.add(fn);
    return () => this.listeners.delete(fn);
  }
Repobility — the code-quality scanner for AI-generated software · https://repobility.com
onCameraEvent method · typescript · L22-L35 (14 LOC)
beau-terminal/src/lib/server/environment/presence.ts
  onCameraEvent(event: CameraEvent) {
    if (event.detected) {
      this.negativeCount = 0;
      this.confidence = event.confidence;
      this.transition('occupied');
    } else {
      this.negativeCount++;
      if (this.negativeCount >= DEBOUNCE_THRESHOLD) {
        this.confidence = event.confidence;
        this.transition('empty');
      }
      // Otherwise stay in current state (debounce)
    }
  }
getSnapshot method · typescript · L37-L39 (3 LOC)
beau-terminal/src/lib/server/environment/presence.ts
  getSnapshot() {
    return { state: this.state, confidence: this.confidence };
  }
transition method · typescript · L41-L45 (5 LOC)
beau-terminal/src/lib/server/environment/presence.ts
  private transition(next: PresenceState) {
    if (this.state === next) return;
    this.state = next;
    for (const fn of this.listeners) fn(next);
  }
parsePresenceMessage function · typescript · L48-L59 (12 LOC)
beau-terminal/src/lib/server/environment/presence.ts
export function parsePresenceMessage(msg: string): CameraEvent | null {
  try {
    const parsed = JSON.parse(msg);
    if (typeof parsed.detected !== 'boolean') return null;
    return {
      detected: parsed.detected,
      confidence: typeof parsed.confidence === 'number' ? parsed.confidence : 0.5,
    };
  } catch {
    return null;
  }
}
SleepMachine class · typescript · L22-L97 (76 LOC)
beau-terminal/src/lib/server/environment/sleep.ts
export class SleepMachine {
  state: SleepState = 'awake';
  isOverridden = false;

  private thresholds: SleepThresholds;
  private settlingCount = 0;
  private listeners = new Set<(state: SleepState) => void>();

  constructor(thresholds?: Partial<SleepThresholds>) {
    this.thresholds = { ...DEFAULT_THRESHOLDS, ...thresholds };
  }

  onChange(fn: (state: SleepState) => void) {
    this.listeners.add(fn);
    return () => this.listeners.delete(fn);
  }

  update(input: SleepInput) {
    if (this.isOverridden) return;

    const isDark = input.lux !== null && input.lux < this.thresholds.luxDark;
    const isStale = input.interactionAge > this.thresholds.interactionStale;
    const isEmpty = input.presenceState === 'empty';

    switch (this.state) {
      case 'awake':
        if (isEmpty && isDark && isStale) {
          this.settlingCount = 1;
          this.transition('settling');
        }
        break;

      case 'settling':
        if (!isEmpty || !isDark || !isStale) {
    
constructor method · typescript · L30-L32 (3 LOC)
beau-terminal/src/lib/server/environment/sleep.ts
  constructor(thresholds?: Partial<SleepThresholds>) {
    this.thresholds = { ...DEFAULT_THRESHOLDS, ...thresholds };
  }
onChange method · typescript · L34-L37 (4 LOC)
beau-terminal/src/lib/server/environment/sleep.ts
  onChange(fn: (state: SleepState) => void) {
    this.listeners.add(fn);
    return () => this.listeners.delete(fn);
  }
update method · typescript · L39-L77 (39 LOC)
beau-terminal/src/lib/server/environment/sleep.ts
  update(input: SleepInput) {
    if (this.isOverridden) return;

    const isDark = input.lux !== null && input.lux < this.thresholds.luxDark;
    const isStale = input.interactionAge > this.thresholds.interactionStale;
    const isEmpty = input.presenceState === 'empty';

    switch (this.state) {
      case 'awake':
        if (isEmpty && isDark && isStale) {
          this.settlingCount = 1;
          this.transition('settling');
        }
        break;

      case 'settling':
        if (!isEmpty || !isDark || !isStale) {
          this.settlingCount = 0;
          this.transition('awake');
        } else {
          this.settlingCount++;
          if (this.settlingCount >= this.thresholds.settlingDuration) {
            this.transition('asleep');
          }
        }
        break;

      case 'asleep':
        if (!isEmpty || input.interactionAge < 10) {
          this.transition('waking');
        }
        break;

      case 'waking':
        this.settlingCount = 0;
        
Repobility · code-quality intelligence platform · https://repobility.com
override method · typescript · L79-L82 (4 LOC)
beau-terminal/src/lib/server/environment/sleep.ts
  override(state: SleepState) {
    this.isOverridden = true;
    this.transition(state);
  }
clearOverride method · typescript · L84-L86 (3 LOC)
beau-terminal/src/lib/server/environment/sleep.ts
  clearOverride() {
    this.isOverridden = false;
  }
getSnapshot method · typescript · L88-L90 (3 LOC)
beau-terminal/src/lib/server/environment/sleep.ts
  getSnapshot() {
    return { state: this.state, isOverridden: this.isOverridden };
  }
‹ prevpage 2 / 9next ›