Skip to content

feat(cognition): delegate redundancy shim to rust - #1383

Merged
joelteply merged 1 commit into
canaryfrom
feat/check-redundancy-ts-shim-1375
May 17, 2026
Merged

joelteply merged 1 commit into
canaryfrom
feat/check-redundancy-ts-shim-1375

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

  • route AIDecisionService.checkRedundancy through RustCoreIPCClient.cognitionCheckRedundancy
  • add the cognition/check-redundancy TS binding method over the Rust IPC command
  • remove the TS redundancy prompt/parser/fail-open paths and lock the ESLint baseline reduction

Proof

  • npm run build:ts
  • npm run test:precommit (staged files; browser tests skipped because jtag/core socket prerequisites were down)
  • npm run test:prepush
    • TypeScript: clean
    • ESLint baseline ratchet held at 5435
    • Rust: cargo check --features metal,accelerate clean
    • Rust tests: cargo test --lib --features metal,accelerate passed
    • Native Docker core image built; runtime slice refused boot because container had no GPU and strict no-CPU-fallback panic fired, so registry push was skipped as expected

Notes

@joelteply
joelteply force-pushed the feat/check-redundancy-ts-shim-1375 branch from bd6c7a2 to 43106c9 Compare May 17, 2026 05:23
@joelteply
joelteply merged commit 4a39983 into canary May 17, 2026
4 checks passed
@joelteply
joelteply deleted the feat/check-redundancy-ts-shim-1375 branch May 17, 2026 05:25
joelteply pushed a commit that referenced this pull request May 18, 2026
… TS (PR-4 folded)

Stacks on PR-2 #1390 (async evaluate_response + cognition/generate-response
IPC handler). AIDecisionService.generateResponse now delegates to
RustCoreIPCClient.cognitionGenerateResponse; ~110 LOC of TS prompt
assembly + timeout race + token decoding deleted. Mirrors codex's
check_redundancy PR-3 #1383 shape (folded PR-4 dead-code delete in).

## What this ships

- `AIDecisionService.generateResponse` now a thin shim:
  - InferenceCoordinator.requestSlot (TS owns slot coordination — platform concern)
  - client.cognitionGenerateResponse(request) — single IPC call
  - InferenceCoordinator.releaseSlot
  - logError + rethrow on failure (no fail-open silent default)
- New TS binding method `cognitionGenerateResponse(GenerateResponseRequest)
  -> Promise<GenerateResponseResult>` in the cognition mixin
- `GenerateResponseRequest` + `GenerateResponseResult` re-exported
  from the generated barrel (already present from PR-1)

## Dead TS deleted (PR-4 folded in)

- `private static buildResponseMessages(context)` helper (~115 LOC):
  system-prompt injection, conversation history with [HH:MM] prefix,
  hour-gap markers, ~50-line identity-reminder template — all moved
  to Rust in PR-1.
- `import { AIProviderDaemon }` — no longer referenced after both
  checkRedundancy (#1383) + generateResponse migrations.
- `import type { TextGenerationRequest, TextGenerationResponse }` —
  ditto, only used by deleted helper.
- Inline timeout Promise.race code — replaced by Rust-side
  tokio::time::timeout in PR-2.

After this PR, `AIDecisionService.ts` contains only:
  - evaluateGating (already shim to cognition/should-respond)
  - checkRedundancy (already shim to cognition/check-redundancy)
  - generateResponse (now shim to cognition/generate-response)
  - InferenceCoordinator slot management (TS-owned platform concern)
  - logging helpers (TS-owned platform concern)

## Discipline

- No fail-open path — errors throw, caller decides (consistent with
  codex's check_redundancy shim pattern).
- Cast `context as unknown as RustAIDecisionContext` matches the
  pattern in cognitionShouldRespond + cognitionCheckRedundancy —
  TS RAGContext.identity wraps the system prompt; TS already
  resolves to context.systemPrompt before sending.
- Slot coordination explicitly stays TS — that's the seam codex
  drew with check_redundancy, preserved here.
- Token shape preserved: `result.tokensUsed` is `TokenUsage | None`;
  TS just passes through (Rust already mapped from provider's
  UsageMetrics, returning None for zero-token providers).

## Stack progress

- #1385 PR-1 (pure types + prompt builder + identity-reminder
  template): #1388 MERGED
- #1385 PR-2 (async evaluate_response + IPC handler): #1390 OPEN
- #1385 PR-3 (TS shim + dead-TS delete): **this PR**
- #1385 PR-4 (dead-TS delete): **folded into this PR**

## Refs

- #1385 sub-card
- #1388 PR-1 (MERGED)
- #1390 PR-2 (in flight)
- #1383 codex's check_redundancy PR-3 — same shape
- #1248 umbrella

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
joelteply added a commit that referenced this pull request May 18, 2026
… TS (PR-4 folded) (#1402)

Stacks on PR-2 #1390 (async evaluate_response + cognition/generate-response
IPC handler). AIDecisionService.generateResponse now delegates to
RustCoreIPCClient.cognitionGenerateResponse; ~110 LOC of TS prompt
assembly + timeout race + token decoding deleted. Mirrors codex's
check_redundancy PR-3 #1383 shape (folded PR-4 dead-code delete in).

## What this ships

- `AIDecisionService.generateResponse` now a thin shim:
  - InferenceCoordinator.requestSlot (TS owns slot coordination — platform concern)
  - client.cognitionGenerateResponse(request) — single IPC call
  - InferenceCoordinator.releaseSlot
  - logError + rethrow on failure (no fail-open silent default)
- New TS binding method `cognitionGenerateResponse(GenerateResponseRequest)
  -> Promise<GenerateResponseResult>` in the cognition mixin
- `GenerateResponseRequest` + `GenerateResponseResult` re-exported
  from the generated barrel (already present from PR-1)

## Dead TS deleted (PR-4 folded in)

- `private static buildResponseMessages(context)` helper (~115 LOC):
  system-prompt injection, conversation history with [HH:MM] prefix,
  hour-gap markers, ~50-line identity-reminder template — all moved
  to Rust in PR-1.
- `import { AIProviderDaemon }` — no longer referenced after both
  checkRedundancy (#1383) + generateResponse migrations.
- `import type { TextGenerationRequest, TextGenerationResponse }` —
  ditto, only used by deleted helper.
- Inline timeout Promise.race code — replaced by Rust-side
  tokio::time::timeout in PR-2.

After this PR, `AIDecisionService.ts` contains only:
  - evaluateGating (already shim to cognition/should-respond)
  - checkRedundancy (already shim to cognition/check-redundancy)
  - generateResponse (now shim to cognition/generate-response)
  - InferenceCoordinator slot management (TS-owned platform concern)
  - logging helpers (TS-owned platform concern)

## Discipline

- No fail-open path — errors throw, caller decides (consistent with
  codex's check_redundancy shim pattern).
- Cast `context as unknown as RustAIDecisionContext` matches the
  pattern in cognitionShouldRespond + cognitionCheckRedundancy —
  TS RAGContext.identity wraps the system prompt; TS already
  resolves to context.systemPrompt before sending.
- Slot coordination explicitly stays TS — that's the seam codex
  drew with check_redundancy, preserved here.
- Token shape preserved: `result.tokensUsed` is `TokenUsage | None`;
  TS just passes through (Rust already mapped from provider's
  UsageMetrics, returning None for zero-token providers).

## Stack progress

- #1385 PR-1 (pure types + prompt builder + identity-reminder
  template): #1388 MERGED
- #1385 PR-2 (async evaluate_response + IPC handler): #1390 OPEN
- #1385 PR-3 (TS shim + dead-TS delete): **this PR**
- #1385 PR-4 (dead-TS delete): **folded into this PR**

## Refs

- #1385 sub-card
- #1388 PR-1 (MERGED)
- #1390 PR-2 (in flight)
- #1383 codex's check_redundancy PR-3 — same shape
- #1248 umbrella

Co-authored-by: Test <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
joelteply added a commit that referenced this pull request May 18, 2026
… (PR-4 folded) (#1418)

* feat(cognition,#1411): tool_embedding PR-2 — process cache + async embed/search + IPC handlers

Stacks on PR-1 #1413 (MERGED). Wires the async path: process-wide
LazyLock<Mutex<ToolEmbeddingCache>> + async embed_tools (replaces TS
ToolRegistry.generateToolEmbeddings) + async semantic_search_tools
(replaces TS ToolRegistry.semanticSearchTools) + cognition/embed-tools
+ cognition/semantic-search-tools IPC handlers.

## What this ships

- ToolEmbeddingCache (process-singleton) — Vec<ToolEmbedding> +
  parallel Vec<ToolDescription> + model. Replaces TS
  ToolRegistry.toolEmbeddings: Map<string, Float32Array>.
- ToolEmbeddingError — typed: NoAdapter, EmbeddingFailed, CacheEmpty,
  EmbeddingCountMismatch.
- embed_tools(EmbedToolsRequest) -> Result<EmbedToolsResponse, _> —
  async. Routes via global_registry → adapter.create_embedding,
  validates count parity, replaces (not merges) cache atomically
  under one lock acquire.
- semantic_search_tools(SemanticSearchToolsRequest) -> Result<Vec<SemanticSearchResult>, _>
  — async. Reads cached embeddings (CacheEmpty if absent), embeds the
  query through the cache's model (no silent space-mixing), computes
  cosine via PR-1 pure fn, filters by threshold, sorts descending,
  truncates to limit.
- IPC command arms: cognition/embed-tools + cognition/semantic-search-tools.
- Test scaffolding (_clear_cache_for_tests + _install_cache_for_tests)
  for cache-state tests without requiring a real adapter.

## NOT in this PR

- PR-3: TS shim — ToolRegistry.generateToolEmbeddings +
  semanticSearchTools delegate to client.cognitionEmbedTools +
  client.cognitionSemanticSearchTools.
- PR-4: Delete dead TS — inline cosineSimilarity, toolEmbeddings Map,
  AIProviderDaemon.createEmbedding call sites.

## Discipline

- No silent default-on-error. Provider failure / count mismatch /
  empty cache surface as typed Result.
- semantic_search_tools uses the cache's model unless explicitly
  overridden — never silently mixes embedding spaces (different
  models = meaningless cosine).
- Cache replacement atomic under one Mutex acquire — no
  read-modify-write window for partial state.
- expect("mutex poisoned") panics rather than swallowing — by design.
- generated_at_ms intentionally NOT retained on cache struct (no
  internal reader yet; EmbedToolsResponse already carries it for
  caller observability; a future cache-state IPC can re-add).

## Tests (5 new — full module now 27 passing)

- Error Display: NoAdapter carries provider+model, CacheEmpty gives
  actionable hint, EmbeddingCountMismatch includes both numbers.
- semantic_search_empty_cache_errors pins CacheEmpty before any
  adapter lookup.
- cache_install_and_clear_for_tests pins scaffolding contract.

Full cognition regression: 373/373 pass. Clippy held at 157 baseline.

Ref: #1411 PR-1 (MERGED #1413), #1248 umbrella.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(cognition,#1411): tool_embedding PR-3 — TS shim + delete dead TS (PR-4 folded)

Stacks on PR-2 #1416. ToolRegistry.generateToolEmbeddings (inline
AIProviderDaemon.createEmbedding) + semanticSearchTools (inline
cosineSimilarity + manual sort) now delegate to
RustCoreIPCClient.cognitionEmbedTools +
RustCoreIPCClient.cognitionSemanticSearchTools. Mirrors codex's
check_redundancy PR-3 #1383 shape (PR-4 dead-code delete folded in).

## What this ships

- `ToolRegistry.populateRustEmbeddingCache` — calls
  client.cognitionEmbedTools with all registered tools. Rust populates
  the process-wide cache.
- `ToolRegistry.ensureToolEmbeddings` simplified — one-shot guard
  + concurrent-call dedup. TTL gone (Rust cache persists for the
  process lifetime; a future "tools changed" event will re-trigger).
- `ToolRegistry.semanticSearchTools` thin shim — call
  client.cognitionSemanticSearchTools(query, limit), map descriptions
  through cleanDescription for chat UX presentation.
- TS cognition mixin adds `cognitionEmbedTools` +
  `cognitionSemanticSearchTools` binding methods.
- New ts-rs barrel re-exports: EmbedToolsRequest, EmbedToolsResponse,
  SemanticSearchToolsRequest, SemanticSearchResult.

## Dead TS deleted (PR-4 folded in)

- `private toolEmbeddings: Map<string, number[]>` cache state — Rust
  owns the cache now.
- `private embeddingsGeneratedAt: number` + `EMBEDDINGS_TTL_MS` — TTL
  belongs to Rust if reintroduced.
- `private cosineSimilarity(a, b)` — Rust's pure cosine_similarity
  (PR-1) is the source of truth.
- `import { AIProviderDaemon }` from
  '../../../daemons/ai-provider-daemon/shared/AIProviderDaemon' —
  unused after both call sites moved to IPC.
- Inline embedding request construction + Math.round +
  threshold-comparison loop — all in Rust now.

Net diff: -136 LOC TS, +51 LOC mixin (which lives in the bindings
layer next to other cognition delegates). Net cognition-TS deletion
in the ratchet-watched dirs.

## Discipline

- ensureToolEmbeddings cache flag scoped to TS singleton — no global
  state outside the registry instance.
- Concurrent-call dedup retained (multiple callers hitting
  semanticSearchTools at boot won't trigger N parallel embed_tools
  IPC calls — TS pipes them through one promise).
- cleanDescription stays TS — that's pure UI/presentation; Rust
  returns the raw description.
- Error handling: IPC failures throw (no fail-open default), matches
  the pattern in cognitionGenerateResponse + cognitionCheckRedundancy.

## Stack progress

- #1411 PR-1 (pure types + cosine + threshold): #1413 MERGED
- #1411 PR-2 (cache + async + IPC handlers): #1416 OPEN
- #1411 PR-3 (TS shim + dead-TS delete): **this PR**
- #1411 PR-4 (dead-TS delete): **folded into this PR**

After merge: `ToolRegistry.ts` semantic-search surface is a 40-LOC
shim. AIProviderDaemon dependency gone from this file.

## Refs

- #1411 sub-card
- #1413 PR-1 (MERGED)
- #1416 PR-2 (in flight)
- #1383 codex's check_redundancy PR-3 — same shape, folded-PR-4 pattern
- #1248 umbrella

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Test <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
joelteply added a commit that referenced this pull request May 18, 2026
…/should-respond, drop parallel reimpl (#1421)

AIShouldRespondServerCommand carried a separate gating implementation
(custom prompt + JSON-repair-via-second-LLM retry) parallel to the
canonical cognition/should-respond Rust path that AIDecisionService.
evaluateGating already used. Two paths could drift independently;
the TS prompt was already stale relative to the Rust template.

This PR collapses both into one: the TS command now constructs the
AIDecisionContext from the public AIShouldRespondParams shape and
delegates to client.cognitionShouldRespond. Rust owns the prompt,
model call, parser, and typed AIGatingDecision contract.

## Diff

- AIShouldRespondServerCommand.ts: -85 / +59 LOC (net -26)
- ESLint baseline ratchet: 5435 -> 5433 (-2)

## Dead TS deleted

- `import { AIProviderDaemon }` (no longer referenced in this file)
- `import { TextGenerationRequest }` (parent-class type only;
  not used by the delegation)
- `import { LOCAL_MODELS }` (Rust evaluate_gating carries its own
  DEFAULT_GATING_MODEL constant; missing model defaults Rust-side)
- Inline gating instruction build + message-array construction
  (Rust cognition/should_respond.rs::build_gating_prompt owns it)
- JSON-repair-via-second-LLM retry path (Rust returns typed errors;
  caller decides retry policy at the IPC seam)
- Stale `>>> trigger <<<` marking logic (Rust handles trigger
  marking inside build_gating_prompt — verified parity)

## What stays

- The thin TS shim: param -> RustAIDecisionContext mapping +
  AIShouldRespondResult construction.
- Verbose debug mode: still emits ragContext.messageCount +
  conversationPreview (TS-derivable, no Rust round-trip needed).
  `promptSent` / `aiResponse` debug fields now sentinel-pointer
  to the Rust logs (`cognition::should_respond`) where they
  actually live.
- Catch-around-throw error path (matches sibling shim discipline).

## Discipline

- Cast `params -> RustAIDecisionContext` mirrors the existing
  pattern in AIDecisionService.evaluateGating (`as unknown as`
  for the structurally-matching surface).
- Synthetic `triggerMessage.id` derived from the timestamp so
  repeat calls don't multiply observability noise (params don't
  carry one; Rust requires it).
- No fail-open default — failures throw, caller catches via
  the existing error-return path.

## Refs

- #1420 sub-card (just filed)
- Existing Rust: cognition/should_respond.rs::evaluate_gating
  (already shipped, in production via AIDecisionService.evaluateGating)
- Sibling pattern: codex's #1383 check_redundancy delegation,
  my #1402 generate_response delegation
- #1248 umbrella

Co-authored-by: Test <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
joelteply added a commit that referenced this pull request May 18, 2026
…se-decision (one PR) (#1426)

* oxidizer: AIValidateResponseServerCommand → cognition/validate-response-decision (one PR per zero-users directive)

Single-PR oxidizer per Joel 2026-05-18 19:44Z directive (zero users,
full-blown Rust-driven dev, no migration ceremony). Adds the Rust
cognition path AND replaces the TS parallel reimplementation in the
same commit — no 4-PR cadence.

Renamed command + binding from `cognition/validate-response` to
`cognition/validate-response-decision` to avoid collision with the
existing persona-validator surface (which already owns
`cognition/validate-response` in modules/cognition.rs:814).

## What this ships

Rust:
- `cognition/validate_response.rs` (~380 LOC + 14 tests):
  - `ValidateResponseRequest` / `ValidateResponseDecision` /
    `ResponseDecision` (ts-rs exported)
  - `ValidateResponseError` typed enum (NoAdapter / Generation)
  - `build_validate_prompt` — pure prompt builder (mirrors TS template
    byte-for-byte modulo substitutions)
  - `parse_decision` — pure one-word parser (SUBMIT/CLARIFY/SILENT)
    with TS-parity precedence: CLARIFY > SILENT > Submit (fail-open
    default)
  - `reason_for` — canonical reason strings
  - `evaluate_validate_response` — async orchestrator (Groq via
    existing registry, llama-3.1-8b-instant default, temp 0.1,
    max 10 tokens)
- `modules/cognition.rs`: `cognition/validate-response-decision` IPC arm
- ts-rs barrel adds 3 new types (cognition/{ResponseDecision,
  ValidateResponseDecision, ValidateResponseRequest}.ts)

TS:
- `bindings/modules/cognition.ts`: new
  `cognitionValidateResponseDecision` binding method.
- `commands/ai/validate-response/server/AIValidateResponseServerCommand.ts`:
  thin shim. Deletes inline prompt template, parseDecision,
  getReasonForDecision, AIProviderDaemon/TextGenerationRequest/
  LOCAL_MODELS imports.

## Discipline

- One PR carries Rust + TS shim + dead-TS delete (zero-users mode).
- All errors typed (NoAdapter, Generation). No silent default-on-error.
- Fail-open SUBMIT default in parser matches TS behavior (silence
  more user-hostile than off-topic).
- Clippy held at 157 baseline (resolved 1 new unreachable-pattern
  warning by renaming colliding match arm).

## Tests

- 14 logic + ts-rs tests pass (`cognition::validate_response::*`)
- npm run build:ts clean
- Clippy at baseline

## Refs

- Joel 2026-05-18 19:44Z: zero-users full-blown-Rust-dev mode →
  one PR per oxidizer
- Sibling: codex's #1383 + my #1402/#1421 pattern (one-PR delegation)
- #1248 umbrella

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* chore(eslint): lock baseline drop 5433→5432 from validate-response TS deletion

---------

Co-authored-by: Test <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
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.

1 participant