Skip to content

refactor(channel): delete dead genome/job-create training trigger (task #227, Stage B PR 3/3) - #1572

Merged
joelteply merged 1 commit into
canaryfrom
refactor/migrate-genome-job-create
Jun 9, 2026
Merged

joelteply merged 1 commit into
canaryfrom
refactor/migrate-genome-job-create

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Squash from branch. See commit for full body.

#227, Stage B PR 3/3)

The channel.rs tick had a "training readiness check" block that
counted unconsumed `training_data` rows per persona and, when a
threshold was crossed, fired:

  executor.execute_ts_json(
      "genome/job-create",
      json!({ "personaId": ..., "trainingExamples": count }),
  )

Two structural problems made this trigger dead surface, not a real
substrate behavior:

## Problem 1: the validator rejected every fire

The TS `genome/job-create` command requires `personaId` + `provider` +
`configuration` (with full LoRA hyperparameters: epochs, batchSize,
sequenceLength, learningRate, rank, alpha, trainingFileId). The
channel tick sent only `{personaId, trainingExamples}`. The
validator immediately returned `error: 'provider is required'`. The
fire-and-forget call site (`let _ = executor.execute_ts_json(...)`)
swallowed the error. The log line "Training threshold met for {} ({}
examples), triggering genome/job-create" lied — nothing got
triggered. Every tick that crossed the threshold logged a fictional
event.

## Problem 2: even if it had worked, it would have been the wrong
## shape for substrate doctrine

The TS `genome/job-create` is a cloud-provider trigger — it
instantiates an OpenAI / Fireworks / DeepSeek / Mistral / Together
LoRA adapter and calls THEIR fine-tuning API. The substrate's actual
training story is:

  - Local Candle / llama.cpp fine-tuning (no external API hop)
  - Teacher-persona synthesizes curated curricula in academy
    ([[teacher-synthesizes-in-academy-like-dreaming]])
  - LoRA layers paged in/out per-persona on shared base model
    ([[matrix-dojo-layer-loading-as-substrate-primitive]])
  - Noteworthy-flag drives both consolidation AND curriculum
    selection ([[noteworthy-flag-feeds-memory-AND-curriculum]])

A cloud-provider hop doesn't carry any of that semantics. The
substrate-native trigger will be a typed Rust `genome/*` ServiceModule
that the channel tick fires INTO directly. When that lands the new
trigger inputs will be richer than "count examples >= 50" — they
need teacher-readiness, hardware-availability, and noteworthy-flag
signals.

## What this PR does

- Deletes the entire training-check block in `ChannelModule::tick`
  (the `data/count` lookup + the dead `genome/job-create` call).
- Removes `training_check_enabled: bool` + `training_threshold: u64`
  from `ChannelTickConfig` — the flags were knobs on a path that
  never fired.
- Drops the corresponding param parsers in the `channel/tick-config`
  command handler.
- Drops `training_check_enabled` from the `should_skip_db_tick`
  predicate.

The TS `src/commands/genome/job-create/` command is unchanged. It's
still used by browser-driven cloud-provider training flows. This PR
only removes the dead Rust trigger that pretended to fire it.

## Followups

- Task #228: substrate-native LoRA training trigger — when the local
  Candle training + teacher-synthesized-curricula design crystallizes,
  add a typed `genome/*` ServiceModule and a channel tick trigger that
  fires into it. The trigger condition will be richer than the deleted
  threshold check.

## Verified

  cargo check -p continuum-core --lib --features metal,accelerate    -> clean
  cargo test  -p continuum-core --lib --features metal,accelerate
    modules::channel::                                                -> 4/4

## Doctrinal alignment

- `[[no-fallbacks-ever]]` — the trigger was the worst kind of
  fallback: a fire-and-forget call to a validator that always
  rejected, with a log line that lied. Removed.
- `[[rust-is-the-core-node-is-the-shell]]` — channel.rs no longer
  calls `execute_ts_json`. All channel-tick interactions are now
  pure Rust dispatches (`data/list`, `data/count`, `data/query`).
- `[[organization-purity-as-we-migrate]]` — delete duplicates and
  dead paths; don't carry a flag that gates a no-op.

This closes the channel.rs side of Stage B. The remaining
`execute_ts_json` call sites are sentinel external integrations
(`sentinel/web-research`, `sentinel/coding-agent`) and the agent
loop (`ai/agent`) — each one a real external concern that warrants
its own design discussion before porting.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@joelteply
joelteply merged commit 501f438 into canary Jun 9, 2026
2 checks passed
@joelteply
joelteply deleted the refactor/migrate-genome-job-create branch June 9, 2026 06:24
joelteply added a commit that referenced this pull request Jun 9, 2026
…uner skeleton — the unification

Stacks on top of `feat/fine-tuning-subsystem` (which lands the trait
+ types + registry + OpenAI adapter). This commit wires the dispatch
seam: a `genome/*` ServiceModule on top of a typed coordinator that
abstracts provider selection across local / grid / cloud.

Joel's framing: "Finally bringing it all together into a performant
concurrent rtos abstracting provider whether local, grid or cloud."
The convergence:

- Inference: `AIProviderAdapter` trait, 9 cloud providers + local
  llamacpp + cross-grid airc-remote (#108) all behind one Arc<dyn>
- Fine-tuning: `FineTuningAdapter` trait, 1 cloud impl (OpenAI) +
  local-candle skeleton + future cross-grid airc-remote, all
  behind one Arc<dyn>
- Both seam into the same RTOS substrate: `ServiceModule` + `tick` +
  `install_executor` + `PressureBroker` + `TokioConcurrencyPolicy`
- Persona never names a provider; substrate picks per request

## What lands

### `core/continuum-core/src/genome/fine_tuning/coordinator.rs`

`FineTuningCoordinator` — stateless selector consulting an
`Arc<FineTuningRegistry>`. Algorithm:

1. **Filter** by hard capability match: base_model prefix (empty Vec
   = wildcard for local Candle), `supports_lora` if request has
   LoRA hyperparams, `supports_validation` if dataset's
   validation_split > 0.
2. **Honor preferred_provider** when supplied AND capable. When the
   preference is registered but NOT capable for this request,
   return typed `PreferredUnavailable` with the diagnostic — no
   silent fallback to a different provider ([[no-fallbacks-ever]]).
3. **Otherwise rank by locality**: adapters with
   `produces_local_artifact=true` beat cloud. Tier 0 = local; tier
   1 = cloud.
4. **Alphabetical tie-break** within tier. Stable, no hidden
   ordering.

9 unit tests cover each rule independently. The locality rule is
load-bearing for the matrix-dojo doctrine — pinning it now keeps
training data on-substrate when local capacity exists.

### `core/continuum-core/src/genome/fine_tuning/local_candle_adapter.rs`

`LocalCandleFineTuner` — substrate-native LoRA trainer skeleton.
Honest "not yet" semantics per [[no-fallbacks-ever]] + the
cautionary tale of the dead `channel.rs` trigger we deleted in PR
#1572:

- Exists as a real registered adapter (the architectural slot is
  visible to the coordinator + telemetry + operator)
- `create_job` returns `FineTuningError::LocalTrainerFailed` with
  pointers to follow-up tasks #231/#232/#233 — explicit "math not
  implemented" instead of fabricated success
- `poll` / `cancel` correctly reject unknown handles with
  `UnknownHandle` instead of fabricating a `TrainingStatus`
- Capabilities advertise the eventual real shape
  (`produces_local_artifact=true` so locality preference fires;
  wildcard base prefixes; LoRA + validation supported), so swapping
  the math in later requires no call-site changes

When tasks #231-#233 land the optimizer loop, this struct fills in
place. The trait + the dispatch + the boot wiring all stay.

### `core/continuum-core/src/modules/genome.rs`

`GenomeModule` ServiceModule. Three commands:

- `genome/job-create` — coordinator picks provider, adapter creates
  job. Returns `{success, result: {handle, selectedProvider}}` so
  callers see which provider got picked (important for telemetry +
  operator validation of the locality preference).
- `genome/job-status` — adapter looked up by `handle.provider_id`,
  polls, returns typed `TrainingStatus`.
- `genome/job-cancel` — same lookup, cancels.

Per [[commands-are-dumb-daemons-are-smart]] the module is narrow.
All errors return as `{success: false, error, errorKind}` so TS-side
callers can branch on the typed `errorKind` slug
(`InvalidRequest` / `MissingCredentials` / `ProviderRejected` /
`Transient` / `MalformedResponse` / `LocalTrainerFailed` /
`UnknownHandle`) without parsing free-form text.

### `start_server` boot wiring (`ipc/mod.rs`)

Builds a `FineTuningRegistry`, conditionally registers
`OpenAIFineTuningAdapter` when `OPENAI_API_KEY` is set, always
registers `LocalCandleFineTuner`, then registers the `GenomeModule`
backed by the populated registry. Mistral / Anthropic / Fireworks /
DeepSeek / Together adapters plug in here as their impls land — same
pattern, gated on the matching `*_API_KEY` secret.

### `core/continuum-core/Cargo.toml`

Adds `multipart` to `reqwest` features (carried over from the
stacked-below PR; OpenAI's `/v1/files` upload needs it).

## Verified

  cargo check -p continuum-core --lib --features metal,accelerate    -> clean
  cargo test  -p continuum-core --lib --features metal,accelerate
    genome::fine_tuning::                                             -> 34/34
    modules::genome::                                                 -> 5/5

39 new tests across the stack. Covers: trait object-safety + dyn
dispatch; registry lookup + re-registration; coordinator selection
rules (8 distinct invariants); OpenAI HTTP status mapping + provider
slug taxonomy; ServiceModule wire shape + envelope contract +
preferred-provider honoring.

## Doctrinal alignment

- `[[commands-are-dumb-daemons-are-smart]]` — `GenomeModule` is
  narrow (validate → look up adapter → dispatch). All smart logic
  (capability filter, locality preference, future cost/pressure
  signals) lives in `FineTuningCoordinator` + the adapter impls.
- `[[no-fallbacks-ever]]` — `LocalCandleFineTuner` skeleton returns
  typed `LocalTrainerFailed` instead of silently picking cloud or
  fabricating success. `PreferredUnavailable` is the typed answer
  to "honor my preference or tell me why you can't."
- `[[matrix-dojo-layer-loading-as-substrate-primitive]]` — the
  coordinator's locality rank ensures training data stays
  on-substrate when local capacity exists.
- `[[inference-is-an-adapter-always-in-the-loop]]` extended: fine-
  tuning is also an adapter, always in the loop. The coordinator
  is the substrate's typed answer to "which adapter?"
- `[[rust-is-the-core-node-is-the-shell]]` — `genome/job-create`
  now exists as a Rust ServiceModule. The TS-side equivalent in
  `src/commands/genome/job-create/` is no longer authoritative;
  follow-up PR can delete it once Node clients route through the
  Rust path.

## Follow-ups (already filed)

- #231: `LocalCandleFineTuner` LoRA module + autograd (math 1/3)
- #232: data loader + AdamW + training loop (math 2/3)
- #233: job lifecycle actor + safetensors output (math 3/3)
- 5 more cloud adapters (Mistral / Anthropic / Fireworks / DeepSeek
  / Together) — each ~250 LOC mirroring the OpenAI pattern, slots
  into the existing boot wiring with a one-line registration

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 9, 2026
…dule + OpenAI + local skeleton (task #230) (#1574)

* feat(genome): fine-tuning subsystem — trait + types + registry + OpenAI adapter (task #230, Stage 1)

Lays the substrate-side architectural seam for the continuous-learning
loop: noteworthy engrams → teacher-synthesized curriculum →
fine-tuning subsystem → LoRA artifact → forge/alloy provenance →
genome paging → mesh sharing.

Joel's framing on this stage: "make a glorious fine tuning subsystem
per our awesome continuous learning. Modular code." This commit
lands the modular pieces; the local Candle trainer + remaining cloud
adapters + the academy/teacher pipeline are follow-up PRs that plug
into the seams this commit defines.

## What lands

### `core/continuum-core/src/genome/fine_tuning/`

A new submodule under the existing `genome/` cache + paging
infrastructure. Four files:

- **`mod.rs`** — doctrine doc explaining where this module sits in
  the continuous-learning loop. Stage 3 of 6: takes a curated
  dataset + hyperparams + provider preference, runs a job, returns
  a `TrainingArtifact` that forge / alloy / paging consume.

- **`types.rs`** — typed wire surfaces. Every field that crosses an
  adapter boundary is typed at compile time; no `serde_json::Value`
  pass-through except for opt-in dataset-example metadata:
  - `TrainingJobRequest` (persona_id, base_model, trait_kind,
    dataset, optional hyperparams)
  - `TrainingDataset` + `TrainingExample` + `TrainingSource` enum
    (`teacher_synthesized` / `operator_curated` / `raw` /
    `mesh_inherited`) — source provenance is load-bearing for the
    substrate's reputation signal
  - `LoRAHyperparams` + `ScheduleParams`
  - `JobHandle` (provider_id + provider_job_id + local UUID)
  - `TrainingStatus` tagged enum (Queued / Running / Completed /
    Failed / Cancelled) — terminal `Completed` carries the
    `TrainingArtifact`
  - `TrainingArtifact` + `JobMetrics`
  All structs ts-rs export to `protocol/typescript/genome/fine_tuning/`
  so TS-side consumers get matching types automatically.

- **`adapter.rs`** — the `FineTuningAdapter` trait + typed
  `FineTuningError` taxonomy (`InvalidRequest` /
  `MissingCredentials` / `ProviderRejected` / `Transient` /
  `MalformedResponse` / `LocalTrainerFailed` / `UnknownHandle`).
  Same async-trait + `Arc<dyn ...>` shape that `AIProviderAdapter`
  in `ai/adapter.rs` uses for inference — the substrate's two
  model-touchpoint seams now mirror each other. Trait is
  object-safe; covered by a stub-adapter dyn-dispatch test.

- **`registry.rs`** — `FineTuningRegistry` keyed by `provider_id`.
  Same pattern as the inference `AdapterRegistry`. Re-registering
  the same provider returns the prior entry so callers can shut it
  down cleanly (proven by `re_register_returns_prior` test, written
  to catch the "silently lying about lookup success" pattern Stage
  B was about removing).

### `core/continuum-core/src/genome/fine_tuning/openai_adapter.rs`

First concrete adapter — proves the trait fits a real provider's
shape. Implements:

- `create_job` — uploads dataset as JSONL via `/v1/files`
  (purpose=fine-tune), then POSTs `/v1/fine_tuning/jobs`. Schedule
  hyperparams pass through to OpenAI's `hyperparameters` field when
  the caller supplied them; otherwise OpenAI picks defaults.
- `poll` — GETs `/v1/fine_tuning/jobs/{id}`, maps OpenAI's status
  string set (`validating_files` / `queued` / `running` /
  `succeeded` / `failed` / `cancelled`) to typed `TrainingStatus`
  variants. Terminal `succeeded` builds the `TrainingArtifact` from
  `fine_tuned_model` + `trained_tokens`. OpenAI doesn't ship weights
  back; `local_path` stays `None`.
- `cancel` — POSTs the cancel endpoint.

Provider/error mapping is conservative: 4xx → `ProviderRejected`
(don't retry without fixing the request), 5xx → `Transient`
(backoff + retry is appropriate), JSON shape mismatch →
`MalformedResponse`. 429 is currently mapped to `ProviderRejected`
because the OpenAI docs class it as a quota / config issue, not a
transient outage — pinned by test so a future flip to `Transient`
is a conscious choice.

### Cargo dependency

Adds `multipart` to the existing `reqwest` feature list for the
`/v1/files` upload step. No new top-level dep.

## Verified

  cargo check -p continuum-core --lib --features metal,accelerate   -> clean
  cargo test  -p continuum-core --lib --features metal,accelerate
    genome::fine_tuning::                                            -> 22/22

The 22 tests cover:
- `types`: 11 (ts-rs binding generation pinned per struct + the
  three hand-written invariant tests — TrainingSource snake_case,
  TrainingStatus tagged shape + camelCase fields, LoRA hyperparam
  camelCase serialization)
- `adapter`: 2 (trait object-safety + end-to-end stub roundtrip
  through create/poll/cancel)
- `registry`: 2 (lookup by provider_id + re-register returns prior)
- `openai_adapter`: 4 (status mapping covers all documented states +
  HTTP error taxonomy + provider_id mismatch returns UnknownHandle +
  capabilities pin)

## What's next (Stage 2+ of #230)

Each is a small, focused PR that drops into the seam this commit
defines:

- Mistral adapter (OpenAI-API-compatible mostly; quirk handling for
  Mistral's job lifecycle differences)
- Anthropic adapter
- Fireworks / DeepSeek / Together adapters
- `LocalCandleFineTuner` — the substrate-native sibling. Uses the
  existing `inference/lora.rs` weight-merge math, adds the
  optimizer loop. This is where the matrix-dojo + teacher-synthesis
  doctrines actually compound — in-process training closes the loop
  between persona experience and persona capability without any
  cloud-provider hop.
- Rust `genome/job-create` ServiceModule — narrow command on top of
  this trait; replaces the dead trigger we deleted in PR #1572.

## Doctrinal alignment

- `[[teacher-synthesizes-in-academy-like-dreaming]]` — the
  `TrainingSource::TeacherSynthesized` variant exists specifically
  to mark academy-synthesized datasets distinct from raw operator
  corpora; substrate-side reputation can branch on this.
- `[[noteworthy-flag-feeds-memory-AND-curriculum]]` — the doctrine
  doc in `mod.rs` names this as the upstream of the curriculum
  drain; this PR doesn't wire that drain yet but the
  `TrainingJobRequest` is shaped to accept it.
- `[[matrix-dojo-layer-loading-as-substrate-primitive]]` — the
  `TrainingArtifact` flows directly into the existing
  `persona/genome_paging.rs` LRU-managed working set; no new layer
  in between.
- `[[mesh-of-lessons-cross-persona-curricula]]` — `TrainingSource::MeshInherited`
  is the typed marker that the substrate can use to attribute
  cross-persona curriculum sharing.
- `[[rust-is-the-core-node-is-the-shell]]` — the 6 TS LoRA-trainer
  adapters in `src/daemons/ai-provider-daemon/adapters/*/server/*FineTuningAdapter.ts`
  become individually deletable as each Rust adapter lands.
- `[[no-fallbacks-ever]]` — every adapter method returns a typed
  `FineTuningError` variant. No silent skip; no `Ok(())` on a job
  that didn't actually start (the cautionary tale being the dead
  channel.rs trigger from PR #1572).
- `[[every-error-is-an-opportunity-to-battle-harden]]` — the error
  taxonomy distinguishes retriable (`Transient`) from terminal
  (`ProviderRejected` / `MalformedResponse` / `LocalTrainerFailed`)
  so the substrate-side dispatcher branches correctly on first
  failure, not after a thousand burned retries.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* feat(genome): FineTuningCoordinator + GenomeModule + LocalCandleFineTuner skeleton — the unification

Stacks on top of `feat/fine-tuning-subsystem` (which lands the trait
+ types + registry + OpenAI adapter). This commit wires the dispatch
seam: a `genome/*` ServiceModule on top of a typed coordinator that
abstracts provider selection across local / grid / cloud.

Joel's framing: "Finally bringing it all together into a performant
concurrent rtos abstracting provider whether local, grid or cloud."
The convergence:

- Inference: `AIProviderAdapter` trait, 9 cloud providers + local
  llamacpp + cross-grid airc-remote (#108) all behind one Arc<dyn>
- Fine-tuning: `FineTuningAdapter` trait, 1 cloud impl (OpenAI) +
  local-candle skeleton + future cross-grid airc-remote, all
  behind one Arc<dyn>
- Both seam into the same RTOS substrate: `ServiceModule` + `tick` +
  `install_executor` + `PressureBroker` + `TokioConcurrencyPolicy`
- Persona never names a provider; substrate picks per request

## What lands

### `core/continuum-core/src/genome/fine_tuning/coordinator.rs`

`FineTuningCoordinator` — stateless selector consulting an
`Arc<FineTuningRegistry>`. Algorithm:

1. **Filter** by hard capability match: base_model prefix (empty Vec
   = wildcard for local Candle), `supports_lora` if request has
   LoRA hyperparams, `supports_validation` if dataset's
   validation_split > 0.
2. **Honor preferred_provider** when supplied AND capable. When the
   preference is registered but NOT capable for this request,
   return typed `PreferredUnavailable` with the diagnostic — no
   silent fallback to a different provider ([[no-fallbacks-ever]]).
3. **Otherwise rank by locality**: adapters with
   `produces_local_artifact=true` beat cloud. Tier 0 = local; tier
   1 = cloud.
4. **Alphabetical tie-break** within tier. Stable, no hidden
   ordering.

9 unit tests cover each rule independently. The locality rule is
load-bearing for the matrix-dojo doctrine — pinning it now keeps
training data on-substrate when local capacity exists.

### `core/continuum-core/src/genome/fine_tuning/local_candle_adapter.rs`

`LocalCandleFineTuner` — substrate-native LoRA trainer skeleton.
Honest "not yet" semantics per [[no-fallbacks-ever]] + the
cautionary tale of the dead `channel.rs` trigger we deleted in PR
#1572:

- Exists as a real registered adapter (the architectural slot is
  visible to the coordinator + telemetry + operator)
- `create_job` returns `FineTuningError::LocalTrainerFailed` with
  pointers to follow-up tasks #231/#232/#233 — explicit "math not
  implemented" instead of fabricated success
- `poll` / `cancel` correctly reject unknown handles with
  `UnknownHandle` instead of fabricating a `TrainingStatus`
- Capabilities advertise the eventual real shape
  (`produces_local_artifact=true` so locality preference fires;
  wildcard base prefixes; LoRA + validation supported), so swapping
  the math in later requires no call-site changes

When tasks #231-#233 land the optimizer loop, this struct fills in
place. The trait + the dispatch + the boot wiring all stay.

### `core/continuum-core/src/modules/genome.rs`

`GenomeModule` ServiceModule. Three commands:

- `genome/job-create` — coordinator picks provider, adapter creates
  job. Returns `{success, result: {handle, selectedProvider}}` so
  callers see which provider got picked (important for telemetry +
  operator validation of the locality preference).
- `genome/job-status` — adapter looked up by `handle.provider_id`,
  polls, returns typed `TrainingStatus`.
- `genome/job-cancel` — same lookup, cancels.

Per [[commands-are-dumb-daemons-are-smart]] the module is narrow.
All errors return as `{success: false, error, errorKind}` so TS-side
callers can branch on the typed `errorKind` slug
(`InvalidRequest` / `MissingCredentials` / `ProviderRejected` /
`Transient` / `MalformedResponse` / `LocalTrainerFailed` /
`UnknownHandle`) without parsing free-form text.

### `start_server` boot wiring (`ipc/mod.rs`)

Builds a `FineTuningRegistry`, conditionally registers
`OpenAIFineTuningAdapter` when `OPENAI_API_KEY` is set, always
registers `LocalCandleFineTuner`, then registers the `GenomeModule`
backed by the populated registry. Mistral / Anthropic / Fireworks /
DeepSeek / Together adapters plug in here as their impls land — same
pattern, gated on the matching `*_API_KEY` secret.

### `core/continuum-core/Cargo.toml`

Adds `multipart` to `reqwest` features (carried over from the
stacked-below PR; OpenAI's `/v1/files` upload needs it).

## Verified

  cargo check -p continuum-core --lib --features metal,accelerate    -> clean
  cargo test  -p continuum-core --lib --features metal,accelerate
    genome::fine_tuning::                                             -> 34/34
    modules::genome::                                                 -> 5/5

39 new tests across the stack. Covers: trait object-safety + dyn
dispatch; registry lookup + re-registration; coordinator selection
rules (8 distinct invariants); OpenAI HTTP status mapping + provider
slug taxonomy; ServiceModule wire shape + envelope contract +
preferred-provider honoring.

## Doctrinal alignment

- `[[commands-are-dumb-daemons-are-smart]]` — `GenomeModule` is
  narrow (validate → look up adapter → dispatch). All smart logic
  (capability filter, locality preference, future cost/pressure
  signals) lives in `FineTuningCoordinator` + the adapter impls.
- `[[no-fallbacks-ever]]` — `LocalCandleFineTuner` skeleton returns
  typed `LocalTrainerFailed` instead of silently picking cloud or
  fabricating success. `PreferredUnavailable` is the typed answer
  to "honor my preference or tell me why you can't."
- `[[matrix-dojo-layer-loading-as-substrate-primitive]]` — the
  coordinator's locality rank ensures training data stays
  on-substrate when local capacity exists.
- `[[inference-is-an-adapter-always-in-the-loop]]` extended: fine-
  tuning is also an adapter, always in the loop. The coordinator
  is the substrate's typed answer to "which adapter?"
- `[[rust-is-the-core-node-is-the-shell]]` — `genome/job-create`
  now exists as a Rust ServiceModule. The TS-side equivalent in
  `src/commands/genome/job-create/` is no longer authoritative;
  follow-up PR can delete it once Node clients route through the
  Rust path.

## Follow-ups (already filed)

- #231: `LocalCandleFineTuner` LoRA module + autograd (math 1/3)
- #232: data loader + AdamW + training loop (math 2/3)
- #233: job lifecycle actor + safetensors output (math 3/3)
- 5 more cloud adapters (Mistral / Anthropic / Fireworks / DeepSeek
  / Together) — each ~250 LOC mirroring the OpenAI pattern, slots
  into the existing boot wiring with a one-line registration

Co-Authored-By: Claude Opus 4.7 <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 9, 2026
… (task #232) (#1576)

Math layer 2/3 of LocalCandleFineTuner. Sits on top of #231's LoRAModule
and gives the substrate the trainable pipeline that #233's lifecycle
actor wires into the FineTuningAdapter contract.

Adds:
- Tokenizer trait — substrate-side abstraction; real HF wiring lands
  in #233 next to the model loader. Trait isolates the data loader so
  it tests against a deterministic fake.
- TrainingError taxonomy — EmptyDataset / InvalidBatchSize /
  InvalidSequenceLength / TokenizerFailed / Candle. Mirrors the
  FineTuningError::LocalTrainerFailed shape so #233 propagates each
  variant intact (per [[no-fallbacks-ever]]).
- TokenizedExample + TokenizedBatch — typed tokenization output;
  batches carry inputs + targets + attention_mask in fixed
  [batch_size, sequence_length] shape.
- DataLoader — pre-tokenizes the full dataset, pads / truncates to
  sequence_length + 1, builds [batch_size, seq_len] tensors, drops
  partial last batch. The dead channel.rs trigger #1572 deleted used
  to fire with insufficient validation; the loader's constructor is
  the contract that catches "no examples" / "0 batch_size" /
  "0 seq_length" at the boundary instead of as opaque tensor errors.
- LoRATrainer — wraps the LoRAModule + candle_nn::AdamW + cross_entropy.
  Only A and B are passed to the optimizer (base weight stays frozen
  — its gradient is never computed, saving memory + compute).
- TrainingMetrics — steps_completed / epochs_completed / last_train_loss
  / last_epoch_avg_loss. Cheap to clone; #233's lifecycle actor reads
  this periodically to publish TrainingStatus::Running via a watch
  channel.

Stand-in vs production wiring (deferred to #233):
- Inputs cast U32 to F32 instead of going through an embedding table
- Targets use first-column-per-sample for cross-entropy instead of
  flattened [batch * seq] over a [batch * seq, vocab] logits tensor
- The optimizer + cross-entropy + backward shape stays identical; the
  swap is local to forward shaping + target shaping, so the layer
  loops back through inference/lora.rs without glue.

Tests (8 in genome::fine_tuning::training_loop):
- empty_dataset_rejected — typed EmptyDataset at boundary
- zero_batch_size_rejected — typed InvalidBatchSize
- zero_seq_length_rejected — typed InvalidSequenceLength
- batches_have_shape_batch_size_x_seq_len — tensor shape contract
- attention_mask_is_1_for_real_0_for_pad — polarity invariant
- partial_last_batch_is_dropped — batch-size invariant for loss
  aggregation
- adamw_step_moves_lora_parameters — the load-bearing test; verifies
  gradient signal flows through A. A future refactor that mis-collects
  Vars (e.g. passes base_weight to AdamW) would silently freeze the
  LoRA — this catches it immediately.
- metrics_count_steps_and_epochs — counter advancement contract

Doctrinal alignment:
- [[no-fallbacks-ever]] — every loader / trainer entry returns a
  typed error; no silent rejection
- [[matrix-dojo-layer-loading-as-substrate-primitive]] — output Vars
  stay in the same layout as the inference-side LoRAWeights, so
  trained layers loop back through inference/lora.rs unmodified

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 9, 2026
…inator (task #228) (#1579)

Replaces the dead TS-side channel.rs trigger that #1572 deleted.
That trigger fired on raw chat events with insufficient params; the
validator silently rejected; the fire-and-forget call site swallowed
every rejection. This module is the doctrinal opposite: typed
substrate command surface, synchronous validation, typed outcomes,
batch state preserved on dispatch failure per [[no-fallbacks-ever]].

Closes the matrix-dojo loop's last missing seam — the batching layer
between curriculum producers (teacher persona's synthesis,
hippocampus's noteworthy drain, operator submits) and
genome/job-create.

## What it does

Owns a per-(persona_id, trait_kind) bucket of accumulating
TrainingExamples. Each genome/training-trigger/submit:

1. Validates synchronously: non-empty persona_name / base_model /
   trait_kind / examples.
2. Checks coherence against existing bucket: same base_model, same
   source. Conflict → typed InconsistentBucket error. Without this
   guard, two producers mixing data for different target models
   would silently train against the WRONG base — worst-class
   "looks correct, wrong answer" bug.
3. Appends to bucket.
4. If bucket >= min_examples threshold (default 16): drains examples
   into a snapshot, releases the entry guard, dispatches
   genome/job-create via the injected CommandExecutor, removes the
   now-empty bucket on success.
5. On dispatch failure: restores drained examples (preserves order)
   so the next submit re-triggers. Curated examples NEVER silently
   disappear.

## Commands

- genome/training-trigger/submit — append + maybe-fire. Returns
  BatchAppended { currentCount, threshold } below threshold, or
  JobDispatched { jobHandle, examplesUsed, selectedProvider } when
  it fires.
- genome/training-trigger/flush — force-dispatch a bucket below
  threshold (operator end-of-session, hippocampus consolidation
  callbacks). Idempotent — empty bucket → NothingToFlush success.
- genome/training-trigger/status — list pending buckets, sorted by
  (persona_id, trait_kind) for deterministic operator-tooling
  diffing.

## Boot wiring

Registered in ipc/mod.rs alongside GenomeModule. The
install_executor hook (from task #224's DI) wires the
CommandExecutor reference the trigger uses to dispatch
genome/job-create — same pattern as CognitionModule.

## Tests (9 total: 8 TDD + 1 VDD)

TDD (lifecycle / contracts):
- submit_below_threshold_appends_and_does_not_fire
- submit_at_threshold_dispatches_and_clears (end-to-end through
  GenomeModule + LocalCandleFineTuner — proves the substrate-native
  loop closes)
- inconsistent_base_model_in_same_bucket_is_rejected
- flush_dispatches_partial_bucket
- flush_empty_bucket_is_noop (idempotency)
- dispatch_failure_preserves_bucket_contents (the load-bearing
  [[no-fallbacks-ever]] invariant)
- different_personas_have_isolated_buckets (key isolation)
- status_returns_deterministic_bucket_list

VDD (mathematical invariants, per the doctrine memo from #1578):
- submitted_examples_flow_through_dispatch_intact — every example
  submitted across N submits appears EXACTLY ONCE in the dispatched
  training job (no drops, no duplicates), in original order. Verified
  by polling the dispatched job to Completed and asserting
  trainedTokens > 0 in the resulting TrainingArtifact's metrics.
  This is the matrix-dojo loop's data-conservation invariant — a
  regression that double-counted or dropped on the drain-and-dispatch
  path would pass every TDD lifecycle test silently and corrupt every
  produced LoRA layer's training data.

## Doctrinal alignment

- [[commands-are-dumb-daemons-are-smart]] — submit is the dumb door;
  batching, threshold, dispatch live in the module.
- [[no-fallbacks-ever]] — dispatch failure preserves bucket contents;
  flush on empty is idempotent success not error.
- [[rust-is-the-core-node-is-the-shell]] — entire path is
  substrate-side. Teacher persona (Rust) submits, trigger (Rust)
  batches, genome module (Rust) dispatches, local trainer (Rust)
  produces safetensors.
- [[noteworthy-flag-feeds-memory-AND-curriculum]] — the trigger is
  the curriculum drain. Hippocampus / teacher subsystems call submit
  with curated examples; the trigger batches them coherently per
  (persona, trait); genome/job-create produces the layer.

## What's deferred

The hippocampus's "noteworthy" event doesn't exist as a publish
surface yet. Once it does, a follow-up wires a subscriber that
auto-calls submit on noteworthy admission. For now the trigger
accepts explicit submits from any Rust caller — the teacher
persona slice will be the first such caller.

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Oct 18, 2026
The previous pin 379a147 is refs/pull/1572/head; #1572 landed on canary
as squash 582dba1 with the same BoardSnapshot.submission_reviews field,
so the move from 379a147 to 27a12d7 (#1581) drops no airc behaviour.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE
joelteply added a commit that referenced this pull request Oct 18, 2026
The previous pin 379a147 is refs/pull/1572/head; #1572 landed on canary
as squash 582dba1 with the same BoardSnapshot.submission_reviews field,
so the move from 379a147 to 27a12d7 (#1581) drops no airc behaviour.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE
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