← back to PrimeLocus__bmo

Function bodies 413 total

All specs Real LLM only Function bodies
ModeClassifier class · typescript · L46-L101 (56 LOC)
beau-terminal/src/lib/server/personality/mode-classifier.ts
export class ModeClassifier {
	currentMode = 'ambient';
	previousMode: string | null = null;
	private candidateMode: string | null = null;
	private candidateTicks = 0;
	private currentDist = 0;

	update(vector: PersonalityVector): string | null {
		const nearest = findNearest(vector);
		// Always compute distance to the CURRENT mode's centroid (not the nearest)
		const currentCentroidDist = distance(vector, MODE_CENTROIDS[this.currentMode]);

		if (nearest.mode === this.currentMode) {
			this.candidateMode = null;
			this.candidateTicks = 0;
			this.currentDist = currentCentroidDist;
			return null;
		}

		// Update currentDist even when we're drifting away from current mode
		this.currentDist = currentCentroidDist;

		if (nearest.mode === this.candidateMode) {
			this.candidateTicks++;
		} else {
			this.candidateMode = nearest.mode;
			this.candidateTicks = 1;
		}

		if (
			this.candidateTicks >= HYSTERESIS_TICKS &&
			currentCentroidDist - nearest.dist >= HYSTERESIS_DISTANCE
		) {
update method · typescript · L53-L88 (36 LOC)
beau-terminal/src/lib/server/personality/mode-classifier.ts
	update(vector: PersonalityVector): string | null {
		const nearest = findNearest(vector);
		// Always compute distance to the CURRENT mode's centroid (not the nearest)
		const currentCentroidDist = distance(vector, MODE_CENTROIDS[this.currentMode]);

		if (nearest.mode === this.currentMode) {
			this.candidateMode = null;
			this.candidateTicks = 0;
			this.currentDist = currentCentroidDist;
			return null;
		}

		// Update currentDist even when we're drifting away from current mode
		this.currentDist = currentCentroidDist;

		if (nearest.mode === this.candidateMode) {
			this.candidateTicks++;
		} else {
			this.candidateMode = nearest.mode;
			this.candidateTicks = 1;
		}

		if (
			this.candidateTicks >= HYSTERESIS_TICKS &&
			currentCentroidDist - nearest.dist >= HYSTERESIS_DISTANCE
		) {
			this.previousMode = this.currentMode;
			this.currentMode = nearest.mode;
			this.currentDist = nearest.dist;
			this.candidateMode = null;
			this.candidateTicks = 0;
			return this.currentMo
getCandidateMode method · typescript · L90-L92 (3 LOC)
beau-terminal/src/lib/server/personality/mode-classifier.ts
	getCandidateMode(): string | null {
		return this.candidateTicks > 0 ? this.candidateMode : null;
	}
isTransitioning method · typescript · L94-L96 (3 LOC)
beau-terminal/src/lib/server/personality/mode-classifier.ts
	isTransitioning(): boolean {
		return this.candidateTicks > 0;
	}
getDescription method · typescript · L98-L100 (3 LOC)
beau-terminal/src/lib/server/personality/mode-classifier.ts
	getDescription(): string {
		return MODE_DESCRIPTIONS[this.currentMode] ?? '';
	}
computeSelfRegulation function · typescript · L34-L72 (39 LOC)
beau-terminal/src/lib/server/personality/self-regulation.ts
export function computeSelfRegulation(
	vector: PersonalityVector,
	mode: string,
	state: DiscomfortState,
): SelfRegulationResult {
	const deltas: PersonalityVector = { wonder: 0, reflection: 0, mischief: 0 };
	const sources: string[] = [];
	const env = MODE_ENVELOPES[mode];

	// 1. Dominant-dampen: push the most-offending dimension back toward envelope
	if (env && state.envelopeDistance > 0) {
		const dom = findDominantDeviation(vector, env);
		if (dom) {
			deltas[dom.dimension] = dom.sign * DOMINANT_DAMPEN_RATE * state.score * state.coefficient;
			sources.push('self:dominant-dampen');
		}
	}

	// 2. Energy-ceiling: gentle drag when total activation is too high
	const magnitude = Math.sqrt(
		vector.wonder ** 2 + vector.reflection ** 2 + vector.mischief ** 2,
	);
	if (magnitude > ENERGY_CEILING_THRESHOLD) {
		const excess = magnitude - ENERGY_CEILING_THRESHOLD;
		const drag = -ENERGY_CEILING_RATE * excess * state.coefficient;
		deltas.wonder += drag;
		deltas.reflection += drag;
		
updateCoefficient function · typescript · L84-L96 (13 LOC)
beau-terminal/src/lib/server/personality/self-regulation.ts
export function updateCoefficient(state: DiscomfortState): void {
	if (
		state.score > COEFFICIENT_RAMP_DISCOMFORT_THRESHOLD &&
		state.consecutiveHighTicks >= COEFFICIENT_RAMP_TICKS_REQUIRED
	) {
		state.coefficient += COEFFICIENT_RAMP_RATE;
	} else if (state.score < COEFFICIENT_DECAY_DISCOMFORT_THRESHOLD) {
		state.coefficient = 1.0 + (state.coefficient - 1.0) * COEFFICIENT_DECAY_FACTOR;
	}
	// else: deadband (0.3–0.5) — no change

	state.coefficient = Math.max(COEFFICIENT_MIN, Math.min(COEFFICIENT_MAX, state.coefficient));
}
Methodology: Repobility · https://repobility.com/research/state-of-ai-code-2026/
hour function · typescript · L16-L18 (3 LOC)
beau-terminal/src/lib/server/personality/signal-rules.ts
function hour(date: Date): number {
	return date.getHours();
}
isLateNight function · typescript · L20-L23 (4 LOC)
beau-terminal/src/lib/server/personality/signal-rules.ts
function isLateNight(date: Date): boolean {
	const h = hour(date);
	return h >= 1 && h < 5;
}
isDawnDusk function · typescript · L25-L28 (4 LOC)
beau-terminal/src/lib/server/personality/signal-rules.ts
function isDawnDusk(date: Date): boolean {
	const h = hour(date);
	return (h >= 5 && h < 7) || (h >= 17 && h < 20);
}
isStormWeather function · typescript · L30-L34 (5 LOC)
beau-terminal/src/lib/server/personality/signal-rules.ts
function isStormWeather(weather: string | null): boolean {
	if (!weather) return false;
	const w = weather.toLowerCase();
	return w.includes('rain') || w.includes('storm') || w.includes('thunder') || w.includes('drizzle');
}
isClearWarm function · typescript · L36-L40 (5 LOC)
beau-terminal/src/lib/server/personality/signal-rules.ts
function isClearWarm(weather: string | null): boolean {
	if (!weather) return false;
	const w = weather.toLowerCase();
	return w.includes('clear') || w.includes('sunny');
}
isAugust function · typescript · L42-L44 (3 LOC)
beau-terminal/src/lib/server/personality/signal-rules.ts
function isAugust(date: Date): boolean {
	return date.getMonth() === 7;
}
isLateOctober function · typescript · L46-L48 (3 LOC)
beau-terminal/src/lib/server/personality/signal-rules.ts
function isLateOctober(date: Date): boolean {
	return date.getMonth() === 9 && date.getDate() >= 15;
}
computeSignalTargets function · typescript · L163-L166 (4 LOC)
beau-terminal/src/lib/server/personality/signal-rules.ts
export function computeSignalTargets(
	sensor: SensorState,
	activity: ActivitySignals,
): PersonalityVector & { sources: string[] } {
Repobility's GitHub App fixes findings like these · https://github.com/apps/repobility-bot
parseSections function · typescript · L9-L31 (23 LOC)
beau-terminal/src/lib/server/prompt/assembler.ts
export function parseSections(promptText: string): Partial<Record<SectionName, string>> {
  const sections: Partial<Record<SectionName, string>> = {};
  const marker = /<!--\s*SECTION:\s*(\w+)\s*-->/g;
  let match: RegExpExecArray | null;
  const markers: { name: string; contentStart: number; markerStart: number }[] = [];

  while ((match = marker.exec(promptText)) !== null) {
    markers.push({
      name: match[1],
      contentStart: match.index + match[0].length,
      markerStart: match.index,
    });
  }

  for (let i = 0; i < markers.length; i++) {
    const start = markers[i].contentStart;
    const end = i + 1 < markers.length ? markers[i + 1].markerStart : promptText.length;
    const content = promptText.slice(start, end).trim();
    sections[markers[i].name as SectionName] = content;
  }

  return sections;
}
substitutePlaceholders function · typescript · L38-L60 (23 LOC)
beau-terminal/src/lib/server/prompt/assembler.ts
export function substitutePlaceholders(
  text: string,
  values: Record<string, string>,
): string {
  const placeholderPattern = /\{\{(\w+)\}\}/g;

  return text
    .split('\n')
    .filter((line) => {
      if (!placeholderPattern.test(line)) return true;
      placeholderPattern.lastIndex = 0;
      const substituted = line.replace(placeholderPattern, (_, key: string) =>
        values[key] ?? PLACEHOLDER_FALLBACKS[key] ?? ''
      );
      return substituted.trim() !== '';
    })
    .map((line) =>
      line.replace(placeholderPattern, (_, key: string) =>
        values[key] ?? PLACEHOLDER_FALLBACKS[key] ?? ''
      )
    )
    .join('\n');
}
assemblePrompt function · typescript · L66-L86 (21 LOC)
beau-terminal/src/lib/server/prompt/assembler.ts
export function assemblePrompt(
  promptText: string,
  mode: Mode,
  values: Record<string, string>,
): string {
  const sections = parseSections(promptText);
  const parts: string[] = [];

  for (const [name, content] of Object.entries(sections)) {
    const sectionName = name as SectionName;
    const policy = INJECTION_POLICY[sectionName];
    if (!policy) continue;

    const level = policy[mode];
    if (level === 'omit') continue;

    parts.push(substitutePlaceholders(content, values));
  }

  return parts.join('\n\n---\n\n');
}
buildReflexPrompt function · typescript · L92-L125 (34 LOC)
beau-terminal/src/lib/server/prompt/assembler.ts
export function buildReflexPrompt(
  promptText: string,
  mode: Mode,
  values: Record<string, string>,
): string {
  const sections = parseSections(promptText);
  const parts: string[] = [];

  if (sections.CORE_IDENTITY) {
    const firstPara = sections.CORE_IDENTITY.split('\n\n')[0];
    parts.push(substitutePlaceholders(firstPara, values));
  }

  if (sections.VOICE_RULES) {
    parts.push(substitutePlaceholders(sections.VOICE_RULES, values));
  }

  if (sections.CONTEXT) {
    parts.push(substitutePlaceholders(sections.CONTEXT, values));
  }

  if (sections.MODE_PROTOCOL) {
    const modeLines = sections.MODE_PROTOCOL.split('\n');
    const currentModeLine = modeLines.find((l) =>
      l.toLowerCase().startsWith(mode.toLowerCase() + ':') ||
      l.toLowerCase().startsWith(mode.toLowerCase() + ' :')
    );
    if (currentModeLine) {
      parts.push(currentModeLine.trim());
    }
  }

  return parts.join('\n\n');
}
validateVisibility function · typescript · L18-L23 (6 LOC)
beau-terminal/src/lib/server/reflective/journal.ts
export function validateVisibility(value: unknown): Visibility {
  if (typeof value === 'string' && VISIBILITY_LEVELS.includes(value as Visibility)) {
    return value as Visibility;
  }
  return 'private';
}
buildConsentEventValues function · typescript · L32-L46 (15 LOC)
beau-terminal/src/lib/server/reflective/journal.ts
export function buildConsentEventValues(
  eventType: ConsentEventType,
  options: ConsentEventOptions,
) {
  if (!CONSENT_EVENT_TYPES.includes(eventType)) {
    throw new Error(`Invalid consent event type: ${eventType}`);
  }
  return {
    eventType,
    targetId: options.targetId,
    targetType: options.targetType,
    sessionToken: options.sessionToken,
    notes: options.notes,
  };
}
generateSessionToken function · typescript · L49-L53 (5 LOC)
beau-terminal/src/lib/server/reflective/journal.ts
export function generateSessionToken(): string {
  const bytes = new Uint8Array(24);
  crypto.getRandomValues(bytes);
  return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
}
getCollectionPolicy function · typescript · L79-L86 (8 LOC)
beau-terminal/src/lib/server/reflective/memory.ts
export function getCollectionPolicy(mode: string, caller: Caller): CollectionPolicy {
  const entry = COLLECTION_POLICIES[mode];
  if (!entry) return { collections: [...FALLBACK_POLICY.collections], maxTokens: FALLBACK_POLICY.maxTokens };
  // 'internal' follows 'thoughts' rules (Beau's own cognition)
  const key = caller === 'prompt' ? 'prompt' : 'thoughts';
  const policy = entry[key];
  return { collections: [...policy.collections], maxTokens: policy.maxTokens };
}
Open data scored by Repobility · https://repobility.com
getRetrievalPolicy function · typescript · L90-L106 (17 LOC)
beau-terminal/src/lib/server/reflective/memory.ts
export function getRetrievalPolicy(mode: string, context: RetrievalContext): RetrievalPolicy {
  const modePolicy = MODE_POLICIES[mode];

  if (!modePolicy) {
    return {
      sources: ['haikus', 'environment'],
      maxDepth: 'shallow',
      maxResults: context.maxResults ?? DEFAULT_MAX_RESULTS,
    };
  }

  return {
    sources: [...modePolicy.sources],
    maxDepth: modePolicy.maxDepth,
    maxResults: context.maxResults ?? DEFAULT_MAX_RESULTS,
  };
}
validateNoticingCategory function · typescript · L21-L25 (5 LOC)
beau-terminal/src/lib/server/reflective/noticings.ts
export function validateNoticingCategory(value: string): NoticingCategory | null {
  if (BLOCKED_CATEGORIES.includes(value as any)) return null;
  if (ALLOWED_CATEGORIES.includes(value as NoticingCategory)) return value as NoticingCategory;
  return null;
}
isValidStatusTransition function · typescript · L27-L31 (5 LOC)
beau-terminal/src/lib/server/reflective/noticings.ts
export function isValidStatusTransition(from: NoticingStatus, to: NoticingStatus): boolean {
  if (from === to) return false;
  // Forward-only transitions, plus draft can skip to archived
  return STATUS_ORDER[to] > STATUS_ORDER[from];
}
canSurface function · typescript · L39-L47 (9 LOC)
beau-terminal/src/lib/server/reflective/noticings.ts
export function canSurface(noticing: SurfaceCandidate, now: Date = new Date()): boolean {
  if (noticing.status !== 'ready') return false;
  if (noticing.surfacedAt !== null) return false;

  // Enforce minimum observation window
  const created = new Date(noticing.createdAt);
  const daysSinceCreated = (now.getTime() - created.getTime()) / (1000 * 60 * 60 * 24);
  return daysSinceCreated >= MIN_OBSERVATION_WINDOW_DAYS;
}
buildHeader function · typescript · L14-L17 (4 LOC)
beau-terminal/src/lib/server/sitrep.ts
function buildHeader(): string {
	const now = new Date().toISOString();
	return `# BMO Situation Report\n\n**Generated:** ${now}\n**Project:** BMO — Physical robot build (Raspberry Pi 5 + Hailo NPU + custom AI personality)`;
}
buildProjectContext function · typescript · L19-L72 (54 LOC)
beau-terminal/src/lib/server/sitrep.ts
function buildProjectContext(): string | null {
	try {
		const claudeMd = readFileSync(join(process.cwd(), '..', 'CLAUDE.md'), 'utf8');
		// Extract key sections — trim to what another LLM needs
		const lines = claudeMd.split('\n');
		const sections: string[] = [];
		let capturing = false;
		let currentSection: string[] = [];

		const keepHeaders = [
			'## Project Overview',
			'## Architecture Decisions',
			'## Tech Stack',
			'## Design System',
			'## Conventions',
		];
		const stopHeaders = [
			'## Development',
			'## Key Files',
			'## Deep Reference',
			'## Repo Structure',
		];

		for (const line of lines) {
			if (stopHeaders.some((h) => line.startsWith(h))) {
				if (capturing && currentSection.length) {
					sections.push(currentSection.join('\n'));
				}
				capturing = false;
				currentSection = [];
				continue;
			}
			if (keepHeaders.some((h) => line.startsWith(h))) {
				if (capturing && currentSection.length) {
					sections.push(currentSection.join('\n'));
				}
buildIdentitySection function · typescript · L74-L99 (26 LOC)
beau-terminal/src/lib/server/sitrep.ts
function buildIdentitySection(): string | null {
	const parts: string[] = [];

	const artifact = getEmergenceArtifact();
	if (artifact) {
		parts.push(`- **Emergence:** ${artifact.emergenceTimestamp}`);
		parts.push(`- **Soul Code Haiku:** ${artifact.haikuText}`);
		if (artifact.modelUsed) parts.push(`- **Emergence Model:** ${artifact.modelUsed}`);
	}

	const natal = getActiveNatalProfile();
	if (natal) {
		parts.push(`- **Birth:** ${natal.birthTimestamp} (${natal.timezone})`);
		parts.push(`- **Location:** ${natal.locationName}`);
		if (natal.summaryText) parts.push(`- **Natal Summary:** ${natal.summaryText}`);
	}

	const voice = getActiveVoiceModel();
	if (voice) {
		parts.push(`- **Active Voice:** ${voice.versionName} (${voice.engine})`);
		if (voice.trainingNotes) parts.push(`- **Voice Notes:** ${voice.trainingNotes}`);
	}

	if (!parts.length) return null;
	return `## Identity\n\n${parts.join('\n')}`;
}
buildCurrentStateSection function · typescript · L101-L122 (22 LOC)
beau-terminal/src/lib/server/sitrep.ts
function buildCurrentStateSection(): string | null {
	const state = getState();
	const lines: string[] = [];

	lines.push(`- **Mode:** ${state.mode}`);
	lines.push(`- **Expression:** ${state.faceState}`);
	lines.push(`- **Online:** ${state.online ? 'yes' : 'no'}`);
	lines.push(`- **Sleep:** ${state.sleepState}`);
	lines.push(`- **Presence:** ${state.presenceState}`);
	if (state.lux !== null) lines.push(`- **Lux:** ${state.lux} (${state.luxLabel})`);
	if (state.weatherSummary) lines.push(`- **Weather:** ${state.weatherSummary}`);
	if (state.seasonalContext) lines.push(`- **Season:** ${state.seasonalContext}`);
	lines.push(`- **Resolume:** ${state.resolumeActive ? 'LIVE' : 'off'}`);
	if (state.currentBpm) lines.push(`- **BPM:** ${state.currentBpm}`);
	if (state.currentClip) lines.push(`- **Clip:** ${state.currentClip}`);
	if (state.wellnessSessionActive) {
		lines.push(`- **Wellness:** ${state.wellnessDeviceName} at ${state.wellnessActualTemp ?? '?'}°F (${state.wellnessHeatingState})`);
Generated by Repobility's multi-pass static-analysis pipeline (https://repobility.com)
buildBuildProgressSection function · typescript · L124-L165 (42 LOC)
beau-terminal/src/lib/server/sitrep.ts
function buildBuildProgressSection(): string | null {
	const allParts = db.select().from(schema.parts).all();
	const allSteps = db.select().from(schema.softwareSteps).all();
	const allPhases = db.select().from(schema.softwarePhases).orderBy(asc(schema.softwarePhases.order)).all();

	if (!allParts.length && !allSteps.length) return null;

	const lines: string[] = [];

	// Workshop stats
	const received = allParts.filter((p) => p.status === 'delivered' || p.status === 'installed').length;
	const totalCost = allParts.reduce((sum, p) => sum + (p.price ?? 0), 0);
	const stepsDone = allSteps.filter((s) => s.done).length;

	lines.push(`- **Parts:** ${received}/${allParts.length} received ($${totalCost.toFixed(2)} total)`);
	lines.push(`- **Software Steps:** ${stepsDone}/${allSteps.length} complete`);

	// Blocked / shipping parts
	const blocked = allParts.filter((p) => p.status === 'ordered' || p.status === 'shipped');
	if (blocked.length) {
		lines.push('');
		lines.push('**Waiting on:**');
buildIdeasAndTasksSection function · typescript · L167-L198 (32 LOC)
beau-terminal/src/lib/server/sitrep.ts
function buildIdeasAndTasksSection(): string | null {
	const allIdeas = db.select().from(schema.ideas).all();
	const allTodos = db.select().from(schema.todos).all();

	const openIdeas = allIdeas.filter((i) => !i.done);
	const openTodos = allTodos.filter((t) => !t.done);

	if (!openIdeas.length && !openTodos.length) return null;

	const lines: string[] = [];
	const priorityOrder: Record<string, number> = { high: 0, medium: 1, low: 2 };

	if (openIdeas.length) {
		lines.push('**Open Ideas:**');
		const sorted = [...openIdeas].sort((a, b) => (priorityOrder[a.priority] ?? 1) - (priorityOrder[b.priority] ?? 1));
		for (const idea of sorted) {
			lines.push(`- [${idea.priority}] ${idea.text}`);
		}
	}

	if (openTodos.length) {
		if (lines.length) lines.push('');
		lines.push('**Open Tasks:**');
		const sorted = [...openTodos].sort((a, b) => (priorityOrder[a.priority] ?? 1) - (priorityOrder[b.priority] ?? 1));
		for (const todo of sorted) {
			const section = todo.section ? ` (${todo.section}
buildRecentActivitySection function · typescript · L200-L214 (15 LOC)
beau-terminal/src/lib/server/sitrep.ts
function buildRecentActivitySection(): string | null {
	const recent = db
		.select()
		.from(schema.activityLog)
		.orderBy(desc(schema.activityLog.id))
		.limit(15)
		.all();

	if (!recent.length) return null;

	const lines = recent.map(
		(a) => `- **${a.entityType}** ${a.action}: ${a.summary} (${a.createdAt})`
	);
	return `## Recent Activity\n\n${lines.join('\n')}`;
}
buildHaikusSection function · typescript · L216-L231 (16 LOC)
beau-terminal/src/lib/server/sitrep.ts
function buildHaikusSection(): string | null {
	const recent = db
		.select()
		.from(schema.haikus)
		.orderBy(desc(schema.haikus.id))
		.limit(5)
		.all();

	if (!recent.length) return null;

	const lines = recent.map((h) => {
		const meta = [h.mode, h.trigger].filter(Boolean).join(', ');
		return `> ${h.text.replace(/\n/g, ' / ')}\n> — _${meta}_`;
	});
	return `## Recent Haikus\n\n${lines.join('\n\n')}`;
}
buildDispatchesSection function · typescript · L233-L253 (21 LOC)
beau-terminal/src/lib/server/sitrep.ts
function buildDispatchesSection(): string | null {
	const recent = db
		.select()
		.from(schema.dispatches)
		.orderBy(desc(schema.dispatches.id))
		.limit(10)
		.all();

	if (!recent.length) return null;

	const lines = recent.map((d) => {
		const parts: string[] = [];
		if (d.tier) parts.push(`tier=${d.tier}`);
		if (d.model) parts.push(`model=${d.model}`);
		if (d.routingReason) parts.push(`reason=${d.routingReason}`);
		if (d.durationMs) parts.push(`${d.durationMs}ms`);
		const meta = parts.length ? ` (${parts.join(', ')})` : '';
		return `- ${d.querySummary ?? 'unknown query'}${meta}`;
	});
	return `## Recent Dispatches\n\n${lines.join('\n')}`;
}
buildEnvironmentSection function · typescript · L255-L280 (26 LOC)
beau-terminal/src/lib/server/sitrep.ts
function buildEnvironmentSection(): string | null {
	const snapshot = db
		.select()
		.from(schema.environmentSnapshots)
		.orderBy(desc(schema.environmentSnapshots.id))
		.limit(1)
		.get();

	if (!snapshot) return null;

	const lines: string[] = [];
	lines.push(`- **Timestamp:** ${snapshot.timestamp}`);
	if (snapshot.presenceState) lines.push(`- **Presence:** ${snapshot.presenceState}`);
	if (snapshot.sleepState) lines.push(`- **Sleep:** ${snapshot.sleepState}`);
	if (snapshot.lux !== null) lines.push(`- **Lux:** ${snapshot.lux}`);
	if (snapshot.contextMode) lines.push(`- **Mode:** ${snapshot.contextMode}`);
	if (snapshot.seasonalSummary) lines.push(`- **Season:** ${snapshot.seasonalSummary}`);
	if (snapshot.weatherJson) {
		try {
			const w = JSON.parse(snapshot.weatherJson);
			if (w.description) lines.push(`- **Weather:** ${w.description}`);
		} catch { /* skip */ }
	}

	return `## Environment (Last Snapshot)\n\n${lines.join('\n')}`;
}
buildCreativeSection function · typescript · L282-L303 (22 LOC)
beau-terminal/src/lib/server/sitrep.ts
function buildCreativeSection(): string | null {
	const sessions = db
		.select()
		.from(schema.resolumeSessions)
		.orderBy(desc(schema.resolumeSessions.id))
		.limit(5)
		.all();

	if (!sessions.length) return null;

	const lines = sessions.map((s) => {
		const parts: string[] = [];
		parts.push(`**${s.sessionName ?? `Session #${s.id}`}**`);
		parts.push(`started ${s.startedAt}`);
		if (s.endedAt) parts.push(`ended ${s.endedAt}`);
		parts.push(`status: ${s.status}`);
		if (s.bpmAvg) parts.push(`avg BPM: ${s.bpmAvg}`);
		if (s.venue) parts.push(`venue: ${s.venue}`);
		return `- ${parts.join(' | ')}`;
	});
	return `## Creative Sessions (Resolume)\n\n${lines.join('\n')}`;
}
buildWellnessSection function · typescript · L305-L335 (31 LOC)
beau-terminal/src/lib/server/sitrep.ts
function buildWellnessSection(): string | null {
	const state = getState();
	const sessions = db
		.select()
		.from(schema.wellnessSessions)
		.orderBy(desc(schema.wellnessSessions.id))
		.limit(5)
		.all();

	if (!sessions.length && !state.wellnessSessionActive) return null;

	const lines: string[] = [];

	if (state.wellnessSessionActive) {
		lines.push(`- **Active Session:** ${state.wellnessDeviceName} at ${state.wellnessTargetTemp ?? '?'}°F (actual: ${state.wellnessActualTemp ?? '?'}°F)`);
		lines.push(`- **Heating State:** ${state.wellnessHeatingState}`);
	}

	for (const s of sessions) {
		const parts: string[] = [];
		parts.push(`**${s.displayName}**`);
		parts.push(`started ${s.startedAt}`);
		if (s.endedAt) parts.push(`ended ${s.endedAt}`);
		if (s.targetTemp) parts.push(`target: ${s.targetTemp}°F`);
		if (s.peakTemp) parts.push(`peak: ${s.peakTemp}°F`);
		if (s.durationSeconds) parts.push(`${Math.round(s.durationSeconds / 60)}min`);
		lines.push(`- ${parts.join(' | ')}`);
	}

Methodology: Repobility · https://repobility.com/research/state-of-ai-code-2026/
buildIntegrationsSection function · typescript · L337-L345 (9 LOC)
beau-terminal/src/lib/server/sitrep.ts
function buildIntegrationsSection(): string | null {
	const integs = db.select().from(schema.integrations).all();
	if (!integs.length) return null;

	const lines = integs.map(
		(i) => `- ${i.icon} **${i.name}** — ${i.status}${i.lastSeen ? ` (last seen: ${i.lastSeen})` : ''}`
	);
	return `## Integrations\n\n${lines.join('\n')}`;
}
buildEntityLinksSection function · typescript · L347-L355 (9 LOC)
beau-terminal/src/lib/server/sitrep.ts
function buildEntityLinksSection(): string | null {
	const links = db.select().from(schema.entityLinks).all();
	if (!links.length) return null;

	const lines = links.map(
		(l) => `- ${l.sourceType}:${l.sourceId} → ${l.relationship} → ${l.targetType}:${l.targetId}`
	);
	return `## Entity Links\n\n${lines.join('\n')}`;
}
getTimeOfDay function · typescript · L44-L53 (10 LOC)
beau-terminal/src/lib/server/thoughts/dispatcher.ts
export function getTimeOfDay(hour: number): string {
  if (hour >= 0 && hour <= 4) return 'late night';
  if (hour >= 5 && hour <= 7) return 'early morning';
  if (hour >= 8 && hour <= 11) return 'morning';
  if (hour >= 12 && hour <= 13) return 'midday';
  if (hour >= 14 && hour <= 16) return 'afternoon';
  if (hour >= 17 && hour <= 19) return 'evening';
  if (hour >= 20 && hour <= 22) return 'night';
  return 'late night'; // hour 23
}
deriveTone function · typescript · L58-L72 (15 LOC)
beau-terminal/src/lib/server/thoughts/dispatcher.ts
export function deriveTone(vector: { wonder: number; reflection: number; mischief: number }): string {
  const { wonder, reflection, mischief } = vector;

  // All below floor → quiet
  if (wonder < 0.3 && reflection < 0.3 && mischief < 0.3) return 'quiet';

  // Find dominant dimension
  const max = Math.max(wonder, reflection, mischief);

  if (reflection === max && reflection > 0.5) return 'contemplative';
  if (mischief === max && mischief > 0.5) return 'wry';
  if (wonder === max && wonder > 0.5) return 'warm';

  return 'present';
}
isInHaikuWindow function · typescript · L78-L90 (13 LOC)
beau-terminal/src/lib/server/thoughts/dispatcher.ts
export function isInHaikuWindow(hour: number): boolean {
  for (const [start, end] of HAIKU_WINDOWS) {
    if (end <= 24) {
      // Normal window — no wrap
      if (hour >= start && hour < end) return true;
    } else {
      // Wrap window — e.g. [23, 25]: covers 23, 0, 1
      // end % 24 = 1, but we want to include hour 1, so use <=
      if (hour >= start || hour <= (end % 24)) return true;
    }
  }
  return false;
}
ThoughtDispatcher class · typescript · L94-L194 (101 LOC)
beau-terminal/src/lib/server/thoughts/dispatcher.ts
export class ThoughtDispatcher {
  private readonly getInterpretation: () => string;

  constructor(getInterpretation: () => string) {
    this.getInterpretation = getInterpretation;
  }

  /**
   * Select a ThoughtType based on budget, trigger, novelty, and time.
   *
   * @param state     Current BeauState (subset)
   * @param budget    Today's budget counters + cap flags
   * @param trigger   Source trigger string (e.g. 'idle', 'lux_change')
   * @param isNovelty Whether this tick was flagged as a novelty spike
   * @param rng       Optional deterministic RNG — defaults to Math.random
   * @param hour      Override current hour (for testing); defaults to new Date().getHours()
   */
  selectType(
    state: DispatchableState,
    budget: DailyBudgetStatus,
    trigger: string,
    isNovelty: boolean,
    rng: () => number = Math.random,
    hour: number = new Date().getHours(),
  ): ThoughtType | null {
    // 1. Hard cap — nothing gets through
    if (budget.atTotalCap) return null;
constructor method · typescript · L97-L99 (3 LOC)
beau-terminal/src/lib/server/thoughts/dispatcher.ts
  constructor(getInterpretation: () => string) {
    this.getInterpretation = getInterpretation;
  }
selectType method · typescript · L111-L150 (40 LOC)
beau-terminal/src/lib/server/thoughts/dispatcher.ts
  selectType(
    state: DispatchableState,
    budget: DailyBudgetStatus,
    trigger: string,
    isNovelty: boolean,
    rng: () => number = Math.random,
    hour: number = new Date().getHours(),
  ): ThoughtType | null {
    // 1. Hard cap — nothing gets through
    if (budget.atTotalCap) return null;

    // 2. Haiku window check
    const inWindow = isInHaikuWindow(hour);
    if (inWindow && state.personalityVector.reflection > 0.5 && !budget.atHaikuCap) {
      return 'haiku';
    }

    // 3. Sensor trigger → observation
    if (
      trigger.startsWith('lux_') ||
      trigger.startsWith('presence_') ||
      trigger.startsWith('activity_')
    ) {
      return 'observation';
    }

    // 4. Novelty weighted random
    if (isNovelty) {
      const roll = rng();
      if (roll < 0.6) return 'reaction';
      if (roll < 0.9) {
        // 30% haiku band — fall back to reaction if at cap
        return budget.atHaikuCap ? 'reaction' : 'haiku';
      }
      return 'observation';
Repobility's GitHub App fixes findings like these · https://github.com/apps/repobility-bot
buildBrainRequest method · typescript · L157-L162 (6 LOC)
beau-terminal/src/lib/server/thoughts/dispatcher.ts
  buildBrainRequest(
    type: ThoughtType,
    state: DispatchableState,
    trigger: string,
    isNovelty: boolean,
  ): Extract<BrainRequestV1, { kind: 'thought.generate' }> {
computeExpiresAt method · typescript · L187-L193 (7 LOC)
beau-terminal/src/lib/server/thoughts/dispatcher.ts
  computeExpiresAt(type: ThoughtType): string {
    const base = DECAY_TTL[type];
    // Random value in [-DECAY_VARIANCE, +DECAY_VARIANCE]
    const jitter = (Math.random() * 2 - 1) * DECAY_VARIANCE;
    const ttlMs = base * (1 + jitter);
    return new Date(Date.now() + ttlMs).toISOString();
  }
registerThoughtSystem function · typescript · L10-L18 (9 LOC)
beau-terminal/src/lib/server/thoughts/index.ts
export function registerThoughtSystem(
  queue: ThoughtQueue,
  publish: PublishFn,
  topics: typeof TOPICS,
) {
  _queue = queue;
  _publish = publish;
  _topics = topics;
}
‹ prevpage 5 / 9next ›