Skip to content

Elegance audit: type safety, Rust cognition, social signals, cascading curriculum - #286

Merged
joelteply merged 8 commits into
mainfrom
feature/elegance-audit-type-safety
Mar 8, 2026
Merged

joelteply merged 8 commits into
mainfrom
feature/elegance-audit-type-safety

Conversation

@joelteply

@joelteply joelteply commented Mar 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • God class decomposition: PersonaResponseGenerator (1501 lines → 4 modules), PersonaMessageEvaluator (1157 lines → 3 modules)
  • TimingConfig centralization: Scattered magic numbers → single PersonaTimingConfig source of truth
  • Safety systems re-enabled: Circuit breaker (was disabled at 999999), energy thermodynamics with floor
  • Echo chamber + content dedup migrated to Rust: Microsecond-fast ring buffers replace TS implementations
  • AI discovery: user/list command via CommandGenerator — personas can discover each other
  • Gates → social signals: 3 hard-blocking gates (rate limit, directed mention, echo chamber) converted to SocialSignals struct passed through to LLM prompt. The LLM decides for itself whether to speak, not dumb heuristic vetoes. Only 3 hard gates remain: response cap, sleep mode, self-message (system protection)
  • Cascading Curriculum Architecture: Long-horizon LoRA training with temporal credit assignment, competitive cohorts (AP classroom effect), class projects, Recipe→Academy→Genome closed loop, distillation progression (remote→local), genomic repository (Docker Hub for LoRA adapters)

Key architectural decisions

  • Social awareness is INFORMATION for the LLM, not algorithmic constraints. Organic personas decide for themselves
  • Signal pipeline: Rust (μs collection) → IPC → evaluator → generator → assembler → system prompt
  • Remote API students run on someone else's GPUs. Local GPU only pays for LoRA training. Architecture that runs on a MacBook Air
  • Cascading curricula: late-stage failures generate retroactive training signals for early-stage decisions

Test plan

  • 27/27 Rust evaluator tests pass (including new signal tests)
  • npm run build:ts — zero errors
  • npm start — system comes up
  • Personas respond in chat with social signals flowing through prompts
  • Verified via cognition logs: Social signals present: true (ai_recent=N)
  • Verified via prompt captures: 197 prompts contain [Social Awareness] block

…afety

Tier 1: Eliminate `as any` casts in genome commands (proper typed construction)
Tier 2A: PersonaResponseGenerator (1501→~1150 lines) → extract PersonaPromptAssembler,
  PersonaResponseValidator, PersonaEngagementDecider
Tier 2B: PersonaMessageEvaluator → extract PersonaMessageGate, PersonaTrainingSignalExtractor
Tier 3: PersonaTimingConfig centralizes all timing constants (cadence, energy, echo chamber,
  dedup, inbox aging, generation timeout, circuit breaker)
Tier 4A: Re-enable energy thermodynamics with sane rates + 0.1 floor (no death spiral)
Tier 4B: Circuit breaker: 999999→10 failures, 5s→60s cooldown
… command

Rust migration (voice latency reduction):
- message_cache.rs: per-room ring buffer + FNV-1a content dedup (13 tests)
- evaluator.rs: Gate 6 echo chamber in full_evaluate pipeline (26 tests)
- cognition.rs: 3 new IPC commands (cache-message, check-content-dedup, record-content)
- CognitionMixin + RustCognitionBridge: TS bindings for new IPC commands
- PersonaMessageGate: feeds Rust cache on every new message, removed TS echo chamber
- PersonaMessageEvaluator: removed isEchoChamber call (now Rust Gate 6)
- PersonaResponseGenerator: removed dead ContentDeduplicator (Rust handles dedup)

user/list command (AI discovery):
- Generated via CommandGenerator with full scaffold
- Queries users with filters: type, status, provider, capability
- Returns lightweight UserSummary (no sensitive fields)
- Tool descriptions updated for user/list, collaboration/dm, collaboration/live/start
- Verified: AIs successfully discover each other and report findings
Copilot AI review requested due to automatic review settings March 8, 2026 14:37

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR refactors persona cognition and response generation by moving high-frequency gating/dedup logic into Rust, centralizing timing constants in a shared TS config, and adding a new user/list command for AI-safe user discovery.

Changes:

  • Added Rust-side per-room message caching + echo chamber gate and Rust content dedup IPC endpoints, wiring them through TS bridges/bindings.
  • Introduced PersonaTimingConfig as a TS central config and replaced scattered timing “magic numbers” (energy floor, cadence, circuit breaker, inbox dedup window, generation limits).
  • Added user/list command (spec, schemas, server+browser implementations, docs/tests) and updated tool parameter descriptions.

Reviewed changes

Copilot reviewed 38 out of 39 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
src/workers/continuum-core/src/persona/unified.rs Adds per-persona Rust message cache + content dedup state into PersonaCognition.
src/workers/continuum-core/src/persona/mod.rs Exposes the new message_cache module and re-exports its public types.
src/workers/continuum-core/src/persona/message_cache.rs Implements per-room ring-buffer cache + hash-based content dedup, with unit tests.
src/workers/continuum-core/src/persona/evaluator.rs Adds echo chamber as a new gate and extends full_evaluate to accept RecentMessageCache.
src/workers/continuum-core/src/modules/cognition.rs Wires cache/dedup into cognition module commands and passes cache into full_evaluate.
src/workers/continuum-core/bindings/modules/cognition.ts Adds TS IPC bindings for cache-message + content dedup check/record.
src/system/user/server/modules/RustCognitionBridge.ts Adds TS bridge helpers to feed Rust message cache and use Rust content dedup.
src/system/user/server/modules/PersonaTrainingSignalExtractor.ts Extracts training-signal detection into a dedicated module.
src/system/user/server/modules/PersonaToolDefinitions.ts Updates parameter descriptions and adds user/list override descriptions.
src/system/user/server/modules/PersonaTimingConfig.ts Introduces centralized timing constants for persona subsystems.
src/system/user/server/modules/PersonaState.ts Re-enables energy thermodynamics with a floor and uses PersonaTimingConfig for cadence/rates.
src/system/user/server/modules/PersonaResponseValidator.ts Extracts response cleaning + combined Rust validation gates into a helper module.
src/system/user/server/modules/PersonaResponseGenerator.ts Converts generator into an orchestrator delegating prompt assembly/validation/engagement; uses timing config.
src/system/user/server/modules/PersonaPromptAssembler.ts Extracts prompt assembly logic (system prompt, artifacts, voice mode, identity reminder).
src/system/user/server/modules/PersonaMessageGate.ts Adds TS-side post-inference adequacy checks + feeds Rust cache via events.
src/system/user/server/modules/PersonaMessageEvaluator.ts Removes TS echo-chamber gate, delegates training-signal + post-inference gating to extracted modules.
src/system/user/server/modules/PersonaInbox.ts Replaces hard-coded aging/dedup windows with PersonaTimingConfig.
src/system/user/server/modules/PersonaEngagementDecider.ts Extracts dormancy/engagement decision logic from response generation.
src/system/user/server/modules/ContentDeduplicator.ts Points dedup constants at PersonaTimingConfig (legacy TS dedup helper).
src/system/user/server/PersonaUser.ts Registers the Rust bridge for message-cache feeding.
src/shared/version.ts Bumps library version constant.
src/shared/generated-command-constants.ts Adds USER_LIST command constant.
src/server/generated.ts Registers the new user/list server command in the generated registry.
src/package.json Bumps package version.
src/package-lock.json Bumps lockfile package version.
src/generator/specs/user-list.json Adds generator spec for user/list.
src/generated-command-schemas.json Updates generated command schemas (adds user/list entry and regenerates).
src/daemons/ai-provider-daemon/shared/BaseAIProviderAdapter.ts Re-enables circuit breaker using PersonaTimingConfig thresholds.
src/commands/user/list/test/unit/UserListCommand.test.ts Adds generated reference unit test scaffold for user/list.
src/commands/user/list/test/integration/UserListIntegration.test.ts Adds generated reference integration test scaffold for user/list.
src/commands/user/list/shared/UserListTypes.ts Adds shared types and executor helper for user/list.
src/commands/user/list/server/UserListServerCommand.ts Implements server-side user/list query and filtering.
src/commands/user/list/package.json Adds command package metadata/scripts for user/list.
src/commands/user/list/browser/UserListBrowserCommand.ts Adds browser-side delegating implementation for user/list.
src/commands/user/list/README.md Adds documentation for user/list usage and testing.
src/commands/user/list/.npmignore Adds ignore rules for packaging the command.
src/commands/genome/train/server/GenomeTrainServerCommand.ts Improves type safety by removing any casts for async params/config creation.
src/commands/genome/job-create/server/GenomeJobCreateServerCommand.ts Improves provider validation typing without any casts.
src/browser/generated.ts Registers the new user/list browser command in the generated registry.
Files not reviewed (1)
  • src/package-lock.json: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/shared/version.ts Outdated
*/

export const VERSION = '1.0.8717';
export const VERSION = '1.0.8722';

Copilot AI Mar 8, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Version numbers are inconsistent across the repo: VERSION is updated to 1.0.8722 here, but src/package.json and src/package-lock.json are at 1.0.8723. This can break release/build metadata expectations; align all version sources to the same value (or document which is authoritative).

Suggested change
export const VERSION = '1.0.8722';
export const VERSION = '1.0.8723';

Copilot uses AI. Check for mistakes.
Comment on lines +15 to +28
// =============================================================================
// TIMING CONFIG (mirrors PersonaTimingConfig.ts — single source of truth in Rust)
// =============================================================================

/// Echo chamber: lookback window (2 minutes)
const ECHO_CHAMBER_WINDOW_MS: u64 = 2 * 60 * 1000;
/// Echo chamber: AI message count threshold before gating
const ECHO_CHAMBER_AI_THRESHOLD: usize = 5;
/// Max messages cached per room
const MAX_CACHED_PER_ROOM: usize = 50;
/// Content dedup: time window (60 seconds)
const CONTENT_DEDUP_WINDOW_MS: u64 = 60_000;
/// Content dedup: max tracked entries
const CONTENT_DEDUP_MAX_ENTRIES: usize = 50;

Copilot AI Mar 8, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Rust message cache duplicates timing constants (echo chamber window/threshold, dedup window, cache sizes) that are also defined in PersonaTimingConfig.ts, but the header comment says this is a “single source of truth”. This is misleading and makes future drift likely; either wire these values from a shared config/generator or adjust the comment to clarify they must be kept in sync manually (and ideally add a sync test).

Copilot uses AI. Check for mistakes.
Comment on lines +419 to +442
let result = cache.check_echo_chamber(room, false, false, now);
assert!(
result.check_time_us < 1000,
"Echo chamber check should be <1ms, was {}us",
result.check_time_us
);
}

#[test]
fn test_content_dedup_check_is_fast() {
let mut dedup = ContentDeduplicator::new();
let room = Uuid::new_v4();
let now = now_ms();

for i in 0..50 {
dedup.record(&format!("Message {i}"), room, now - (50 - i) * 1000);
}

let result = dedup.is_duplicate("New message", room, now);
assert!(
result.check_time_us < 1000,
"Content dedup should be <1ms, was {}us",
result.check_time_us
);

Copilot AI Mar 8, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The “performance” unit tests assert <1ms (1000us) based on Instant timing, which is likely to be flaky on slower/contended CI runners (and the timing includes scheduler noise). Consider removing these from unit tests, converting to benchmarks, or relaxing the threshold to something deterministic (or gating it behind an ignored/feature-flagged test).

Copilot uses AI. Check for mistakes.
Comment on lines +26 to +50
// Rust bridges to feed — all personas' bridges get message cache updates
private static _rustBridges: Set<RustCognitionBridge> = new Set();

private readonly personaId: UUID;
private readonly personaName: string;
private readonly log: (message: string, ...args: any[]) => void;

constructor(
personaId: UUID,
personaName: string,
log: (message: string, ...args: any[]) => void,
) {
this.personaId = personaId;
this.personaName = personaName;
this.log = log;
PersonaMessageGate.initMessageCache();
}

/**
* Register a Rust bridge so it receives message cache updates.
* Called once per persona after bridge initialization.
*/
registerRustBridge(bridge: RustCognitionBridge): void {
PersonaMessageGate._rustBridges.add(bridge);
}

Copilot AI Mar 8, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PersonaMessageGate keeps a static Set of RustCognitionBridge instances, but there’s no deregistration path when a persona shuts down/reconnects. This can retain bridges indefinitely and keep attempting IPC calls on dead bridges. Add an unregister method (and call it from PersonaUser.shutdown / bridge.disconnect), or store weak refs / prune the set on failures.

Copilot uses AI. Check for mistakes.
Comment on lines +588 to +591
// Feed Rust-side message cache for echo chamber detection (Gate 6 of full_evaluate)
if (this._rustCognition) {
this.messageEvaluator.messageGate.registerRustBridge(this._rustCognition);
}

Copilot AI Mar 8, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PersonaUser registers its Rust cognition bridge with PersonaMessageGate, but there’s no corresponding deregistration during shutdown. If personas are restarted/recreated, the static bridge set can accumulate stale bridges. Consider tracking the registration and unregistering it inside PersonaUser.shutdown() (or when the bridge disconnects).

Copilot uses AI. Check for mistakes.
Comment on lines +8 to +10
import type { CommandParams, CommandResult, CommandInput, JTAGContext } from '@system/core/types/JTAGTypes';
import { createPayload, transformPayload } from '@system/core/types/JTAGTypes';
import { SYSTEM_SCOPES } from '@system/core/types/SystemScopes';

Copilot AI Mar 8, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file imports several symbols that are not used (e.g., createPayload, SYSTEM_SCOPES, JTAGContext). These unused imports add noise and can trigger lint/noUnusedLocals failures depending on TS config; please remove them or use them if they’re intended for the payload helper pattern.

Suggested change
import type { CommandParams, CommandResult, CommandInput, JTAGContext } from '@system/core/types/JTAGTypes';
import { createPayload, transformPayload } from '@system/core/types/JTAGTypes';
import { SYSTEM_SCOPES } from '@system/core/types/SystemScopes';
import type { CommandParams, CommandResult, CommandInput } from '@system/core/types/JTAGTypes';
import { transformPayload } from '@system/core/types/JTAGTypes';

Copilot uses AI. Check for mistakes.
Comment on lines +22 to +71
async execute(params: UserListParams): Promise<UserListResult> {
const limit = params.limit ?? 50;

// Build ORM filter from params
const filter: Record<string, string> = {};
if (params.type) filter.type = params.type;
if (params.status) filter.status = params.status;

const result = await ORM.query<UserEntity>({
collection: COLLECTIONS.USERS,
filter,
limit,
sort: [{ field: 'lastActiveAt', direction: 'desc' }],
}, 'default');

if (!result.success || !result.data) {
return createUserListResultFromParams(params, {
success: false,
users: [],
total: 0,
error: 'Failed to query users',
});
}

// Hydrate and apply post-query filters (provider, capability)
let users: UserSummary[] = result.data.map(row => {
const entity = { ...row.data, id: row.id } as UserEntity;
return this.toSummary(entity);
});

// Post-query filter: provider (stored inside modelConfig JSON)
if (params.provider) {
const providerLower = params.provider.toLowerCase();
users = users.filter(u => u.provider?.toLowerCase() === providerLower);
}

// Post-query filter: capability
if (params.capability) {
const cap = params.capability as keyof UserSummary['capabilities'];
users = users.filter(u => {
const capabilities = u.capabilities as Record<string, boolean>;
return capabilities[cap] === true;
});
}

return createUserListResultFromParams(params, {
success: true,
users,
total: users.length,
});

Copilot AI Mar 8, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

total is returned as users.length, but the command applies limit in the ORM query before post-query filters (provider/capability). This means total is not the total number of matching users, and results can be missing matches that fall outside the initial limited query. Consider computing total via ORM.count() (with the same base filters) and applying post-filters before slicing to limit (or otherwise adjusting the API/description to reflect the limited/filtered semantics).

Copilot uses AI. Check for mistakes.
Rust evaluator.rs: rate limit, directed mention, and echo chamber gates
converted from hard vetoes to SocialSignals struct passed through to LLM.
Only 3 hard gates remain: response cap, sleep mode, self-message (system
protection). Everything else is social awareness the LLM uses to make its
own decision about whether to speak.

Signal pipeline: Rust (μs collection) → IPC → PersonaMessageEvaluator →
PersonaUser → PersonaResponseGenerator → PersonaPromptAssembler →
[Social Awareness] block in system prompt.

27/27 Rust tests pass. Verified E2E: personas respond with real social
context (ai_messages_recent, human_spoke_recently, directed mentions,
response counts). Zero extra compute — signals piggyback on existing
inference call.
Temporal credit assignment: late-stage failures generate retroactive
training signals for early-stage decisions. Stages form dependency
graphs, not flat lists. Constraints (M1, 60fps, type safety) are
present from Stage 1, not introduced later.

Extends Academy Dojo with CascadingTeacherPipeline, retroactive
grading, temporal-weighted loss, and CodingAgent integration for
real coding environments in each stage.
Multiple students (Claude, DeepSeek, local Candle) take the same
cascading exam simultaneously. After each round, top solutions are
shared as learning material. Weaker models train on stronger models'
patterns -- distilling knowledge by merely being together.

API students run on remote GPUs (free compute for us). Only LoRA
training step uses local GPU. Comparative training pairs from
teacher's ranked grading produce the highest-value training data.
Recipe defines WHAT. Genome assembles existing LoRAs (never ground
zero). Academy auto-designs curriculum FROM recipe targeting only
skill gaps. Cohort trains collaboratively (class project). Better
LoRAs deposit back into genome. Next recipe starts from higher floor.

Compounding effect: iteration 1 trains everything from scratch,
iteration 20 is mostly assembly + light fine-tuning on gaps.
Four-phase path from remote-heavy to fully local: remote APIs are
scaffolding, knowledge distills into LoRA adapters over time.

Docker-like adapter management: pull/push/prune/inspect with full
provenance (cascade scores, cohort rankings, distillation lineage).
Integrates with existing genome paging for runtime activation.
@joelteply joelteply changed the title Elegance audit: type safety, Rust migration, AI discovery Elegance audit: type safety, Rust cognition, social signals, cascading curriculum Mar 8, 2026
- Add PersonaMessageGate.unregisterRustBridge() + call from shutdown
- Remove unused imports from UserListTypes.ts
- Fix user/list to query all then filter+slice (total reflects reality)
- Mark Rust perf tests as #[ignore] (flaky on CI, run manually)
- Clarify message_cache.rs timing constants sync with TS
@joelteply
joelteply merged commit d442134 into main Mar 8, 2026
2 of 5 checks passed
@joelteply
joelteply deleted the feature/elegance-audit-type-safety branch March 8, 2026 16:46
joelteply added a commit that referenced this pull request Aug 7, 2026
…trigger the paths filter its PR trigger already had (#291)

ts-eslint-baseline-ratchet, ts-persona-cognition-ratchet and
ts-persona-forbidden-strings-ratchet have failed 100 out of 100 runs, with no
green since 2026-07-05. All three for the same reason, and it is not a real
finding: they check `src/`, which moved to `legacy/src/` in e46d968 (task #83).
check-eslint-baseline.sh:48 hard-exits 2 with "src directory not found".

The asymmetry is the whole bug. Each workflow's `pull_request` trigger carries a
`paths:` filter scoped to `src/**`; the `push` trigger carries none. So on PRs
they correctly stayed quiet, and on every single push to canary they fired into
a directory that no longer exists.

That is three red X's on every push, for a month, that everyone has correctly
learned to disregard — and a board people ignore is worse than no board. It also
means any NEW check we add inherits that contempt, which makes this a
prerequisite for the beta gate (#286), not cosmetics.

The push trigger now carries the same filter as its PR sibling. Nothing is
deleted and no baseline is regenerated: the guard is intact and resumes the
instant those paths exist again. It fires only when its target actually changes.

DELIBERATELY NOT DECIDED HERE: whether the legacy TS shell should be gated at
all. #83 says location is the CI-exclusion signal, which points at retiring
these outright — that is Joel's call, and repointing them at `legacy/src/**`
would be me making it quietly.

Same shape as the rest of today: a correct mechanism, configured on one of its
two paths.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants