Module: Insika::Wiring::Graph

Defined in:
lib/insika/wiring/graph.rb

Overview

SHARED composition core for both roots: the minimal wiring (config/wiring.rb) and the concrete deployment (config/deployment.rb) were two near-identical composition roots. The duplication — backend→stores, event stream, registries + policy builtins, capability registry, hooks, the Executor, and the core Command Bus — lives here now; each root only layers on what legitimately differs (profiles, plain-vs-overlay tool registry, catalogs, guardrails config, context providers, and the root-specific bus commands).

Two phases, no magic (a block would hit dynamic-constant assignment in the roots, which promote everything to public constants):

1. `spine(backend:)` — the parameter-free infra spine.
2. `build(spine:, ...)` — assembles the Executor + Command Bus on top, given
 the root's divergent collaborators. This is where the 6 CORE commands
 (incl. pause_task/approve_action) are registered — which is what removes
 the config.ru / serve_real.rb patch that used to bolt them on afterwards.

Defined Under Namespace

Classes: Result, Spine

Class Method Summary collapse

Class Method Details

.backend_from_env(env = ENV) ⇒ Object

Backend by config: INSIKA_DB set → durable SQLite (survives restart, the prerequisite for Recovery); missing → ephemeral Memory (dev/demo). The same rule lived verbatim in both roots. Dual-read honors the legacy HARNESS_DB alias.



28
29
30
31
# File 'lib/insika/wiring/graph.rb', line 28

def backend_from_env(env = ENV)
  db = Insika::EnvSchema.read("INSIKA_DB", env)
  db && !db.empty? ? Insika::Stores::SQLite.new(path: db) : Insika::Stores::Memory.new
end

.build(spine:, profiles:, tool_registry:, tool_catalog:, skill_catalog:, prompt_catalog:, guardrails:, context_providers:, edge_limiter: nil, executor_extra: {}) ⇒ Object

assemble the graph on top of a spine.

tool_registry: effective registry the Executor uses (plain REGISTRY at the base; OverlayToolRegistry in the deployment). guardrails: a Safety::Factory — its input_guardrail becomes the single middleware and its output_validator the after-task hook, so both wirings compose identically. executor_extra: optional Executor kwargs a root adds (deployment passes settings_store + tool_trace_store; the base passes none). edge_limiter: optional EdgeLimiter. It goes BEFORE the InputGuardrail so a flood can't spend the LLM moderator; nil = no edge (parity).



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# File 'lib/insika/wiring/graph.rb', line 161

def build(spine:, profiles:, tool_registry:, tool_catalog:, skill_catalog:,
          prompt_catalog:, guardrails:, context_providers:, edge_limiter: nil,
          executor_extra: {})
  # the save_artifact tool: a REGISTRY tool registered OPTIONAL (the
  # per-agent allowlist is the switch — an agent that did not name it
  # cannot call it). Registered in the shared code registry, so both
  # roots (base registry + the deployment's overlay, which composes it)
  # expose it. The gem's require lives IN the factory block (loaded on
  # the 1st instance, turn time -> wiring-load stays gem-free).
  register_artifact_tool(spine)
  spine.hooks.register(:task, after: guardrails.output_validator)
  middleware = Insika::MiddlewareStack.new([edge_limiter, guardrails.input_guardrail].compact)

  context_builder = Insika::ContextBuilder.new(
    providers: context_providers, event_stream: spine.event_stream, hooks: spine.hooks
  )
  policy_engine = Insika::Policy::Engine.new(
    policy_registry: spine.policy_registry, event_stream: spine.event_stream
  )

  # Always built: the registry starts empty, so `record` finds no
  # channel and returns nil on every turn — the cost of wiring it is one nil
  # check per completed turn, and the alternative is a second wiring path that
  # only production exercises.
  channel_delivery = Insika::ChannelDelivery.new(
    channels: spine.channel_registry, outbox: spine.outbox_store,
    session_store: spine.session_store, event_stream: spine.event_stream,
    shadow_pairs: spine.shadow_pair_store
  )

# WS3 provider reliability (retries/backoff/fallback/breaker) is ALWAYS wired —
# the profile's `reliability` data gates it, so the bare wiring is unchanged.
reliability = Insika::Reliability.new(circuit_store: spine.circuit_state,
                                      event_stream: spine.event_stream)
executor = Insika::Executor.new(
  context_builder: context_builder, policy_engine: policy_engine,
  middleware: middleware, hooks: spine.hooks,
  tool_registry: tool_registry, skill_catalog: skill_catalog, profiles: profiles,
  session_store: spine.session_store, task_store: spine.task_store,
  checkpoint_store: spine.checkpoint_store, event_stream: spine.event_stream,
  workflow_registry: spine.workflow_registry, pending_action_store: spine.pending_action_store,
  capability_registry: spine.capability_registry, tool_catalog: tool_catalog,
  memory_store: spine.memory_store,
  content_filter_factory: guardrails.content_filter_factory, # stream redaction
  delegation_store: spine.delegation_store, # async delegation durability
  channel_delivery: channel_delivery, # out-of-band reply delivery
  reliability: reliability, # WS3: retries/fallback/breaker (data-gated)
  grounding_enforcer: guardrails.grounding_enforcer, # :enforce cut
  # the follow-up stores — the ChatBuilder wires the
  # schedule/cancel_followup tools on them (parity when no pack declares).
  contact_store: spine.contact_store,
  followup_store: spine.followup_store,
  # the model-visible trace rides executor_extra like the
  # context trace — a module graph that omits it still builds (nil =
  # parity). The base graph wires it over the same backend the context
  # trace uses.
  model_visible_trace_store: Insika::ModelVisibleTraceStore.new(store: spine.backend),
  # the per-turn extraction hook (nil = the loop is off,
  # parity). Gated per-agent by `profile.knowledge`.
  knowledge_store: spine.knowledge_store,
  **executor_extra
)

  # the ONE path that writes proposals, shared by the
  # automatic DistillEngine loop and the bus command behind the Studio's
  # "Run distillation now" button (one code path for both).
  run_distillation = Insika::Commands::RunDistillation.new(
    profiles: profiles, proposal_store: spine.proposal_store,
    session_store: spine.session_store, memory_store: spine.memory_store,
    settings_store: executor_extra[:settings_store],
    event_stream: spine.event_stream
  )

  bus = build_core_bus(spine: spine, profiles: profiles, executor: executor,
                       executor_extra: executor_extra, skill_catalog: skill_catalog,
                       run_distillation: run_distillation)

  # the periodic tick (outbox drain + stale recovery sweep). Built
  # here, after the bus, because its recovery half dispatches resume_task
  # through it; handed to the Executor, which starts it as a child of the
  # turn supervisor in serving mode. `INSIKA_TICK_INTERVAL=0` disables.
  # WS8 retention rides the tick: always built, the settings knob
  # (`retention_days`) gates it — the base graph (no settings_store)
  # reads as OFF.
  executor.tick = Insika::Tick.new(
    store: spine.backend, channel_delivery: channel_delivery,
    recovery: Insika::Recovery.new(
      task_store: spine.task_store, checkpoint_store: spine.checkpoint_store, command_bus: bus
    ),
    retention: Insika::Retention.new(
      store: spine.backend, session_store: spine.session_store,
      task_store: spine.task_store, checkpoint_store: spine.checkpoint_store,
      memory_store: spine.memory_store, outcome_store: spine.outcome_store,
      tool_trace_store: executor_extra[:tool_trace_store],
      context_trace_store: executor_extra[:context_trace_store],
      # the model-visible traces die with their checkpoints.
      model_visible_trace_store: Insika::ModelVisibleTraceStore.new(store: spine.backend),
      outbox_store: spine.outbox_store,
      shadow_pair_store: spine.shadow_pair_store,
      settings_store: executor_extra[:settings_store],
      budget_ledger: spine.budget_ledger, # WS2 counter GC (retention-independent)
      funnel_store: spine.funnel_store, # fold dies with its source
      followup_store: spine.followup_store, # records age out too
      contact_store: spine.contact_store, # cells age out too
      proposal_store: spine.proposal_store, # proposals age out too
      harvest_store: spine.harvest_store, # candidates/log/snapshots too
      artifact_store: spine.artifact_store # reports expire on their own TTL
    ),
    interval: tick_env("INSIKA_TICK_INTERVAL") || Insika::Tick::DEFAULT_INTERVAL,
    stale_after: tick_env("INSIKA_TICK_STALE_AFTER") || Insika::Tick::DEFAULT_STALE_AFTER
  )
  # the tick-driven outcome fold — wired here, after the
  # Tick, because it reads the outcome/funnel stores of the spine and the
  # profiles; the per-pair declaration gates it (nil funnel everywhere =
  # an inert fold). Always built: a pack that declares a funnel later
  # finds its fold already on the tick.
  executor.tick.funnel = Insika::FunnelFold.new(
    outcome_store: spine.outcome_store, funnel_store: spine.funnel_store,
    profiles: profiles, store: spine.backend
  )
  # the tick-driven follow-up firer — the tick's third
  # duty, wired here after the Tick, gated by its own claim window.
  # Always built: a pack that declares followup later finds its firer
  # already on the tick (inert when no profile declares followup).
  executor.tick.followup = Insika::FollowupEngine.new(
    store: spine.backend, followup_store: spine.followup_store,
    contact_store: spine.contact_store, task_store: spine.task_store,
    profiles: profiles, executor: executor, event_stream: spine.event_stream
  )
  # the recurring-schedule firer — the tick's
  # fourth duty, wired here after the Tick, gated by its own claim
  # window. Always built: a pack that declares `schedules` later finds
  # its firer already on the tick (inert when no profile declares one).
  executor.tick.schedule = Insika::ScheduleEngine.new(
    store: spine.backend, schedule_store: spine.schedule_store,
    task_store: spine.task_store, session_store: spine.session_store,
    profiles: profiles, executor: executor, budget_ledger: spine.budget_ledger,
    event_stream: spine.event_stream
  )
  # the distillation engine — the tick-duty that finds idle
  # customer sessions and distills them on its own worker fiber (a
  # supervisor child, started in serving mode next to the tick).
  # Always built: a pack that declares `distill:` later finds its engine
  # already wired — and INERT until one does (the engine gates its start
  # and its passes on a declaring profile).
  executor.distill_engine = Insika::DistillEngine.new(
    store: spine.backend, proposal_store: spine.proposal_store,
    session_store: spine.session_store,
    runner: run_distillation,
    profiles: profiles,
    window: Insika::DistillEngine::DEFAULT_WINDOW
  )
  # the harvest engine — the tick-duty that finds idle,
  # unmined sessions whose agent declares `harvest.enabled` and mines
  # them on its own worker fiber (a supervisor child, started in serving
  # mode next to the tick). Always built: INERT until a profile declares
  # harvest (the engine gates its start and its passes on data). The
  # runner is the same RunHarvest the bus serves, so the manual CLI and
  # the automated loop share one code path.
  run_harvest = Insika::Commands::RunHarvest.new(
    profiles: profiles, harvest_store: spine.harvest_store,
    session_store: spine.session_store, task_store: spine.task_store,
    skill_store: skill_catalog.store, # the harvest's dedup reads the authored skills
    tool_trace_store: executor_extra[:tool_trace_store],
    settings_store: executor_extra[:settings_store],
    negative_list: nil, miner_factory: nil,
    event_stream: spine.event_stream
  )
  executor.harvest_engine = Insika::HarvestEngine.new(
    store: spine.backend, harvest_store: spine.harvest_store,
    session_store: spine.session_store, runner: run_harvest,
    profiles: profiles, window: Insika::HarvestEngine::DEFAULT_WINDOW
  )
  # WS6 operator alerts: answers budget_warning / breaker_open /
  # delivery_failed per agent (`alerts.webhook`) via the outbox+claim
  # pipeline. Always wired — the per-agent data gates it (parity).
  executor.alert_dispatcher = Insika::AlertDispatcher.new(
    event_stream: spine.event_stream, outbox: spine.outbox_store,
    channels: spine.channel_registry, profiles: profiles,
    task_store: spine.task_store, http: Insika::HttpClient.new
  )

  Graph::Result.new(
    backend: spine.backend, event_stream: spine.event_stream,
    session_store: spine.session_store, task_store: spine.task_store,
    checkpoint_store: spine.checkpoint_store, pending_action_store: spine.pending_action_store,
    delegation_store: spine.delegation_store,
    memory_store: spine.memory_store, memory_audit_store: spine.memory_audit_store,
    refinement_store: spine.refinement_store,
    harvest_store: spine.harvest_store,
    artifact_store: spine.artifact_store,
    outbox_store: spine.outbox_store, shadow_pair_store: spine.shadow_pair_store,
    inbound_log: spine.inbound_log,
    outcome_store: spine.outcome_store,
    funnel_store: spine.funnel_store,
    contact_store: spine.contact_store,
    followup_store: spine.followup_store,
    schedule_store: spine.schedule_store,
    proposal_store: spine.proposal_store,
    knowledge_store: spine.knowledge_store,
    token_store: spine.token_store, budget_ledger: spine.budget_ledger,
    circuit_state: spine.circuit_state,
    channel_registry: spine.channel_registry, channel_delivery: channel_delivery,
    code_tool_registry: spine.code_tool_registry,
    tool_registry: tool_registry, workflow_registry: spine.workflow_registry,
    policy_registry: spine.policy_registry, capability_registry: spine.capability_registry,
    tool_catalog: tool_catalog, skill_catalog: skill_catalog, prompt_catalog: prompt_catalog,
    hooks: spine.hooks, guardrails: guardrails, middleware: middleware,
    context_providers: context_providers, context_builder: context_builder,
    policy_engine: policy_engine, profiles: profiles, executor: executor, bus: bus
  )
end

.build_core_bus(spine:, profiles:, executor:, executor_extra: {}, skill_catalog: nil, run_distillation: nil) ⇒ Object

The CORE command surface every root needs — turn essentials + the operator controls (pause/approve) the Studio dispatches. Registering pause_task/ approve_action HERE is the crux of: it retires the config.ru:28-34 patch.



420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
# File 'lib/insika/wiring/graph.rb', line 420

def build_core_bus(spine:, profiles:, executor:, executor_extra: {}, skill_catalog: nil,
                   run_distillation: nil)
  bus = Insika::CommandBus.new
  bus.register(:create_session,
               Insika::Commands::CreateSession.new(session_store: spine.session_store, event_stream: spine.event_stream))
  bus.register(:cancel_task,
               Insika::Commands::CancelTask.new(task_store: spine.task_store, executor: executor))
  bus.register(:pause_task,
               Insika::Commands::PauseTask.new(task_store: spine.task_store, executor: executor))
  bus.register(:approve_action,
               Insika::Commands::ApproveAction.new(pending_action_store: spine.pending_action_store,
                                                    executor: executor, event_stream: spine.event_stream))
  bus.register(:send_message,
               Insika::Commands::SendMessage.new(profiles: profiles, session_store: spine.session_store,
                                                  task_store: spine.task_store, executor: executor,
                                                  inbound_log: spine.inbound_log,
                                                  contact_store: spine.contact_store,
                                                  followup_store: spine.followup_store,
                                                  store: spine.backend))
  bus.register(:resume_task,
               Insika::Commands::ResumeTask.new(profiles: profiles, task_store: spine.task_store,
                                                 checkpoint_store: spine.checkpoint_store, executor: executor))
  # WS1 multi-tenant credentials: per-tenant + operator tokens, stored as
  # hashes. Operator-only BY CONSTRUCTION — the edge refuses a tenant
  # principal on POST /v1/commands, and the handlers re-check meta.
  bus.register(:issue_tenant_token,
               Insika::Commands::IssueTenantToken.new(token_store: spine.token_store,
                                                      event_stream: spine.event_stream))
  bus.register(:revoke_token,
               Insika::Commands::RevokeToken.new(token_store: spine.token_store,
                                                 event_stream: spine.event_stream))
  bus.register(:rotate_tenant_token,
               Insika::Commands::RotateTenantToken.new(token_store: spine.token_store,
                                                       event_stream: spine.event_stream))
  # WS7: a business outcome per conversation (operator or integration).
  bus.register(:record_outcome,
               Insika::Commands::RecordOutcome.new(outcome_store: spine.outcome_store,
                                                   event_stream: spine.event_stream))
  # the incumbent's half of a shadow pair, one command behind
  # both mirror shapes (the mirror call itself + the follow-up route).
  bus.register(:record_shadow_reply,
               Insika::Commands::RecordShadowReply.new(shadow_pairs: spine.shadow_pair_store,
                                                       event_stream: spine.event_stream))
  # WS8 (LGPD): purge one customer's memory + the whole footprint of their
  # sessions (traces, tasks, checkpoints, outbox). The trace stores are
  # deployment components (nil at the base — skipped). the
  # audit collaborator records a content-free purge line.
  bus.register(:forget_customer,
               Insika::Commands::ForgetCustomer.new(
                 memory_store: spine.memory_store, session_store: spine.session_store,
                 tool_trace_store: executor_extra[:tool_trace_store],
                 context_trace_store: executor_extra[:context_trace_store],
                 # the model-visible traces die with the
                 # checkpoints (the same SessionPurge list).
                 model_visible_trace_store: Insika::ModelVisibleTraceStore.new(store: spine.backend),
                 task_store: spine.task_store, checkpoint_store: spine.checkpoint_store,
                 outbox_store: spine.outbox_store,
                 shadow_pairs: spine.shadow_pair_store,
                 audit_store: spine.memory_audit_store,
                 followup_store: spine.followup_store,
                 contact_store: spine.contact_store,
                 proposal_store: spine.proposal_store,
                 event_stream: spine.event_stream
               ))
  # the LGPD access right — export one customer's memory
  # cell as content (the Studio download); the event stays counts-only.
  bus.register(:export_customer_memory,
               Insika::Commands::ExportCustomerMemory.new(
                 memory_store: spine.memory_store, event_stream: spine.event_stream
               ))
  # WS8 (LGPD): purge ONE TENANT's data — sessions and their footprint,
  # memory cells and outcomes. Operator-only by construction (ingress).
  bus.register(:delete_tenant_data,
               Insika::Commands::DeleteTenantData.new(
                 memory_store: spine.memory_store, session_store: spine.session_store,
                 tool_trace_store: executor_extra[:tool_trace_store],
                 context_trace_store: executor_extra[:context_trace_store],
                 # the model-visible traces die with the tenant.
                 model_visible_trace_store: Insika::ModelVisibleTraceStore.new(store: spine.backend),
                 outcome_store: spine.outcome_store,
                 funnel_store: spine.funnel_store, # the fold dies with the tenant
                  followup_store: spine.followup_store,
                  contact_store: spine.contact_store,
                  proposal_store: spine.proposal_store,
                  harvest_store: spine.harvest_store,
                  schedule_store: spine.schedule_store,
                  artifact_store: spine.artifact_store,
                  task_store: spine.task_store, checkpoint_store: spine.checkpoint_store,
                    outbox_store: spine.outbox_store,
                    shadow_pairs: spine.shadow_pair_store,
                    token_store: spine.token_store, # revoked BEFORE the sweep
                    event_stream: spine.event_stream
                  ))
  # the operator's baseline freeze — the number
  # read. Synchronous control command, dispatched from the Studio.
  bus.register(:freeze_funnel_baseline,
               Insika::Commands::FreezeFunnelBaseline.new(
                 funnel_store: spine.funnel_store, profiles: profiles,
                 event_stream: spine.event_stream
               ))
  # the follow-up mutations — the Studio's Cancel button
  # and the channel opt-out event (a tenant principal never reaches the
  # generic command ingress; these ride the same operator-grade path).
  bus.register(:cancel_followup,
               Insika::Commands::CancelFollowup.new(followup_store: spine.followup_store,
                                                    event_stream: spine.event_stream))
  # the report destination's Studio mutation — delete one
  # artifact (the only write on the Artifacts tab; a bus command, like
  # every Studio mutation).
  bus.register(:delete_artifact,
               Insika::Commands::DeleteArtifact.new(artifact_store: spine.artifact_store,
                                                    event_stream: spine.event_stream))
  bus.register(:revoke_contact,
               Insika::Commands::RevokeContact.new(contact_store: spine.contact_store,
                                                   followup_store: spine.followup_store,
                                                   store: spine.backend,
                                                   event_stream: spine.event_stream))
  # the human's answer on a distilled proposal — the ONLY
  # mutation behind the Facts (wiki) page. Synchronous control command.
  bus.register(:resolve_proposal,
               Insika::Commands::ResolveProposal.new(
                 proposal_store: spine.proposal_store,
                 memory_store: spine.memory_store,
                 event_stream: spine.event_stream
               ))
  #  /C10: the gated harvest — the mining pass, the double
  # gate, the human's promote/rollback/dismiss. The BASE graph wires the
  # nil factories (no eval surface, no criterion, no funnel): every flow
  # refuses with a named reason or skips (parity). The deployment root
  # re-registers with the real gate/criterion/negative list.
  bus.register(:run_harvest,
               Insika::Commands::RunHarvest.new(
                 profiles: profiles, harvest_store: spine.harvest_store,
                 session_store: spine.session_store, task_store: spine.task_store,
                 skill_store: skill_catalog.store,
                 tool_trace_store: executor_extra[:tool_trace_store],
                 settings_store: executor_extra[:settings_store],
                 negative_list: nil, miner_factory: nil,
                 event_stream: spine.event_stream
               ))
  bus.register(:gate_harvest,
               Insika::Commands::GateHarvest.new(
                 harvest_store: spine.harvest_store, gate: nil,
                 conversion_gate: nil, criterion: nil,
                 event_stream: spine.event_stream
               ))
  bus.register(:promote_harvest,
               Insika::Commands::PromoteHarvest.new(
                 harvest_store: spine.harvest_store,
                 skill_store: skill_catalog.store,
                 skill_catalog: skill_catalog,
                 profile_source: profiles, criterion: nil, conversion_gate: nil,
                 event_stream: spine.event_stream
               ))
  bus.register(:rollback_harvest,
               Insika::Commands::RollbackHarvest.new(
                 harvest_store: spine.harvest_store,
                 skill_store: skill_catalog.store,
                 skill_catalog: skill_catalog,
                 profile_source: profiles, event_stream: spine.event_stream
               ))
  bus.register(:reject_harvest,
               Insika::Commands::RejectHarvest.new(
                 harvest_store: spine.harvest_store, event_stream: spine.event_stream
               ))
  # the ONE path that writes proposals, served to the
  # Studio's "Run distillation now" button. The same instance the
  # DistillEngine's loop uses, so the manual and the automatic share one
  # code path; the engine keeps the automatic pass when the root does
  # not pass a runner here (nil = the command is not on the bus).
  bus.register(:run_distillation, run_distillation) if run_distillation
  # the demo seed's ONE path — the CLI's `insika demo:seed` builds
  # the same Insika::Demo::Seeder itself (no executor, no bus, from
  # Graph.spine alone), and the Studio's "Seed demo data" button
  # dispatches this bus command; nothing else writes the demo agent.
  config_store = Insika::ConfigStore.new(store: spine.backend)
  demo_seeder = Insika::Demo::Seeder.new(
    profiles: profiles, store: spine.backend, session_store: spine.session_store,
    task_store: spine.task_store, outcome_store: spine.outcome_store,
    funnel_store: spine.funnel_store, followup_store: spine.followup_store,
    refinement_store: spine.refinement_store, pending_action_store: spine.pending_action_store,
    proposal_store: spine.proposal_store, memory_store: spine.memory_store,
    golden_store: Insika::GoldenStore.new(config_store: config_store),
    baseline_store: Insika::BaselineStore.new(config_store: config_store),
    event_stream: spine.event_stream
  )
  bus.register(:seed_demo_data,
               Insika::Commands::SeedDemoData.new(seeder: demo_seeder, event_stream: spine.event_stream))
  bus
end

.load_plugins(graph, env: ENV, bundled_root: nil) ⇒ Object

The boot step behind every root's load_plugins (Server::Boot's first named step). Discovers plugin manifests, validates them, requires the entries and registers their contributions into the ALREADY-BUILT graph — which is safe by construction: every seam the Loader touches resolves at turn time (registries and hooks by name, the middleware stack and the provider list per call, the catalogs on reload), and the step runs single-fiber before the server accepts connections.

Roots, highest precedence first (duplicate id -> first root wins):

1. workspace  — INSIKA_PLUGIN_DIR (the operator's override spot);
2. gems       — whatever called Insika::Plugin.announce (default-enabled);
3. bundled    — `bundled_root` (the repo's plugins/; requires enabling).

INSIKA_PLUGINS enables workspace/bundled ids; INSIKA_PLUGINS_DISABLED is the absolute veto (deny wins, like every allowlist in the engine).



388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# File 'lib/insika/wiring/graph.rb', line 388

def load_plugins(graph, env: ENV, bundled_root: nil)
  announced = Insika::Plugin.announced_roots
  workspace = Insika::EnvSchema.read("INSIKA_PLUGIN_DIR", env)
  roots = ([workspace] + announced + [bundled_root]).compact.map { |d| File.expand_path(d.to_s) }

  result = Insika::Plugin::Loader.new(
    roots: roots,
    registries: {
      tools: graph.code_tool_registry, workflows: graph.workflow_registry,
      policies: graph.policy_registry, capabilities: graph.capability_registry,
      channels: graph.channel_registry, hooks: graph.hooks,
      middleware: graph.middleware, context_providers: graph.context_providers
    },
    enabled: plugin_csv(Insika::EnvSchema.read("INSIKA_PLUGINS", env)),
    disabled: plugin_csv(Insika::EnvSchema.read("INSIKA_PLUGINS_DISABLED", env)),
    announced_roots: announced, event_stream: graph.event_stream
  ).load_all

  # Plugin knowledge joins at the LOWEST precedence: an operator's
  # workspace/authored skill always beats a same-named plugin one.
  graph.skill_catalog.add_roots(result[:skill_dirs])
  graph.prompt_catalog.add_roots(result[:prompt_dirs])
  result
end

.plugin_csv(value) ⇒ Object



413
414
415
# File 'lib/insika/wiring/graph.rb', line 413

def plugin_csv(value)
  value.to_s.split(",").map(&:strip).reject(&:empty?)
end

.register_artifact_tool(spine) ⇒ Object



688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
# File 'lib/insika/wiring/graph.rb', line 688

def register_artifact_tool(spine)
  signing_key = Insika::EnvSchema.read("INSIKA_ARTIFACT_SIGNING_KEY")
  signing_ttl = Insika::EnvSchema.read("INSIKA_ARTIFACT_SIGNING_TTL")
  max_bytes = Insika::EnvSchema.read("INSIKA_ARTIFACT_MAX_BYTES")
  base_url = Insika::Coercion.presence(Insika::EnvSchema.read("INSIKA_PUBLIC_URL"))
  spine.code_tool_registry.register("save_artifact", optional: true) do
    require "ruby_llm"
    require_relative "../tools/save_artifact"
    Insika::Tools::SaveArtifact.new(
      artifact_store: spine.artifact_store,
      base_url: base_url,
      signing_key: signing_key,
      signing_ttl: signing_ttl&.to_i,
      max_bytes: max_bytes&.to_i,
      event_stream: spine.event_stream
    )
  end
end

.register_persona_eval_tool(graph, golden_store:, settings_store:, llm: nil) ⇒ Object

The save_artifact tool, registered OPTIONAL on the shared code registry (the per-agent allowlist is the switch). The signing/base config is bound at registration time from the environment — the tool instance is per-deployment, and the tenant/agent/task bindings arrive per-turn via the deposited turn context. run_persona_eval (C3.1): a QA agent's own probe against a SIBLING agent of THIS SAME graph. Registered OPTIONAL on the shared code registry, same switch as save_artifact — but unlike that one, this is NOT called unconditionally from build: it needs a golden_store and a settings_store (the persona model + judge panel), and neither lives on the spine (the base/minimal wiring builds without either, the same way it builds without a Studio) — so each root calls this itself, once it has both. config/deployment.rb (round1, and the actual production config.ru root) and DSL::Runtime both do.

graph is the ALREADY-RETURNED Graph::Result — bus/executor fully assembled by the time a caller has it to pass here, so GraphChat.new needs no laziness of its own (the tool's own factory block is what is lazy — this method just registers it). llm: — the caller's own RubyLLM::Context, when it has one (DSL::Runtime does; config/deployment.rb does not, and reads the process-wide RubyLLM constant like the rest of that root already does). Forwarded as-is so the tool's OWN persona/judge calls spend the right credentials instead of silently defaulting to nil.



676
677
678
679
680
681
682
683
684
685
686
# File 'lib/insika/wiring/graph.rb', line 676

def register_persona_eval_tool(graph, golden_store:, settings_store:, llm: nil)
  graph.code_tool_registry.register("run_persona_eval", optional: true) do
    require "ruby_llm"
    require_relative "../tools/run_persona_eval"
    Insika::Tools::RunPersonaEval.new(
      golden_store: golden_store, profiles: graph.profiles, tool_registry: graph.tool_registry,
      runtime: GraphChat.new(graph: graph), graph: graph, settings_store: settings_store,
      budget_ledger: graph.budget_ledger, event_stream: graph.event_stream, llm: llm
    )
  end
end

.spine(backend:, extra_policy_builtins: {}) ⇒ Object

the infra spine that is IDENTICAL across roots. extra_policy_ builtins covers the one real divergence (the minimal wiring also registers :workflow_allowlist; the deployment does not expose workflows).



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/insika/wiring/graph.rb', line 43

def spine(backend:, extra_policy_builtins: {})
  session_store        = Insika::SessionStore.new(store: backend)
  task_store           = Insika::TaskStore.new(store: backend)
  checkpoint_store     = Insika::CheckpointStore.new(store: backend)
  pending_action_store = Insika::PendingActionStore.new(store: backend)
  delegation_store     = Insika::DelegationStore.new(store: backend)
  memory_store         = Insika::MemoryStore.new(store: backend)
  # the append-only, content-free audit of OPERATOR memory
  # mutations. Built unconditionally (empty and free when nothing writes)
  # so a deployment that turns it on later finds its audit already durable.
  memory_audit_store  = Insika::MemoryAuditStore.new(store: backend)
  token_store          = Insika::TokenStore.new(store: backend)
  budget_ledger        = Insika::BudgetLedger.new(store: backend)
  circuit_state        = Insika::CircuitState.new(store: backend)
  # the two durable halves of a Shape B channel — the
  # replies still owed to a platform, and the retry window that stops a
  # redelivered webhook from becoming a second turn. Built unconditionally
  # (they are empty and free when no channel is registered) so a deployment
  # that turns a channel on later finds its state already durable.
  outbox_store         = Insika::OutboxStore.new(store: backend)
  # the shadow pair store — one durable record per mirrored
  # exchange, written by our half and the incumbent's. Built unconditionally
  # (empty and free when shadow is off) so turning it on later finds the
  # state already durable, beside the outbox on the same runtime backend.
  shadow_pair_store    = Insika::ShadowPairStore.new(store: backend)
  inbound_log          = Insika::InboundLog.new(store: backend)
  # WS7: business outcomes per conversation, recorded by the operator or
  # the integration (POST /v1/outcomes). Built unconditionally (empty and
  # free when nothing records) so the Studio's scorecard always has a store.
  outcome_store        = Insika::OutcomeStore.new(store: backend)
  # the funnel's durable aggregates — per-day stage counts,
  # fold cursors and baseline snapshots. Built unconditionally (empty and
  # free when no pack declares a funnel) so the fold, the doctor and the
  # Studio always have a store to read/write.
  funnel_store        = Insika::FunnelStore.new(store: backend)
  # the contact-state cells and the follow-up schedule
  # records. Built unconditionally (empty and free when no pack declares
  # followup) so the engine, the tools and the Studio always have stores.
  contact_store       = Insika::ContactStore.new(store: backend)
  followup_store      = Insika::FollowupStore.new(store: backend)
  # the recurring-schedule rows: one row per
  # declared schedule, declaration + runtime state. Built unconditionally
  # (empty and free when no pack declares schedules) so the engine, the
  # doctor and the Studio always have a store.
  schedule_store      = Insika::ScheduleStore.new(store: backend)
  # the distilled proposals + the latched dedup ledger +
  # the per-session markers. Built unconditionally (empty and free when
  # no pack declares distill) so the wiki, the engine and the LGPD
  # purges always have a store.
  proposal_store      = Insika::ProposalStore.new(store: backend)
  # concepts extracted from finished turns. Built
  # unconditionally (empty and free when no pack declares knowledge)
  # so the extractor, the Studio and the LGPD purges always have a
  # store.
  knowledge_store      = Insika::KnowledgeStore.new(store: backend)
  # refinement RUNS (reports over real traffic). Runtime data,
  # same backend as sessions/tasks — the collector and the command that write it
  # are the root's business (deployment-only, like the memory commands).
  refinement_store     = Insika::RefinementStore.new(store: backend)
  # the harvest's durable half — mining runs, the per-
  # candidate lifecycle, the append-only promotion log, the snapshots
  # and the per-session markers. Built unconditionally (empty and free
  # when no pack declares harvest) so the engine, the Studio and the
  # LGPD purges always have a store.
  harvest_store        = Insika::HarvestStore.new(store: backend)
  # the report destination — one record per run, no
  # versioning. Built unconditionally (empty and free when nothing saves)
  # so the tool, the routes, the retention sweep and the tenant purge
  # always have a store.
  artifact_store       = Insika::ArtifactStore.new(store: backend)

  code_tool_registry = Insika::ToolRegistry.new
  workflow_registry  = Insika::WorkflowRegistry.new

  policy_registry = Insika::PolicyRegistry.new
  policy_registry.register(:tool_allowlist, Insika::Policy::Builtin::ToolAllowlist)
  policy_registry.register(:skill_allowlist, Insika::Policy::Builtin::SkillAllowlist)
  policy_registry.register(:approval_required, Insika::Policy::Builtin::ApprovalRequired)
  extra_policy_builtins.each { |name, klass| policy_registry.register(name, klass) }

  Spine.new(
    backend: backend, event_stream: Insika::EventStream.new,
    session_store: session_store, task_store: task_store,
    checkpoint_store: checkpoint_store, pending_action_store: pending_action_store,
    delegation_store: delegation_store,
    memory_store: memory_store, memory_audit_store: memory_audit_store,
    refinement_store: refinement_store,
    harvest_store: harvest_store,
    token_store: token_store, budget_ledger: budget_ledger, circuit_state: circuit_state,
    outbox_store: outbox_store, shadow_pair_store: shadow_pair_store,
    inbound_log: inbound_log,
    outcome_store: outcome_store,
    funnel_store: funnel_store,
    contact_store: contact_store,
    followup_store: followup_store,
    schedule_store: schedule_store,
    proposal_store: proposal_store,
    knowledge_store: knowledge_store,
    artifact_store: artifact_store,
    code_tool_registry: code_tool_registry,
    workflow_registry: workflow_registry, policy_registry: policy_registry,
    capability_registry: Insika::CapabilityRegistry.new, hooks: Insika::Hooks.new,
    channel_registry: Insika::ChannelRegistry.new
  )
end

.tick_env(name, env = ENV) ⇒ Object

an integer tick knob from the env, nil when unset (the caller's default wins). Dual-read honors the deprecated HARNESS_* alias.



35
36
37
38
# File 'lib/insika/wiring/graph.rb', line 35

def tick_env(name, env = ENV)
  value = Insika::EnvSchema.read(name, env)
  value&.to_i
end