Skip to content

fix(#722): SystemOrchestrator spawns + supervises continuum-core-server (closes #722) - #977

Merged
joelteply merged 1 commit into
canaryfrom
fix/722-rust-core-supervisor
May 1, 2026
Merged

joelteply merged 1 commit into
canaryfrom
fix/722-rust-core-supervisor

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

Closes the all-widgets-blank-on-refresh bug (#722). RCA filed in comment 4355290646 — three compounding causes, this PR closes all three.

What changed

Layer A — SystemOrchestrator owns the Rust core lifecycle

  • New CORE_START + CORE_READY milestones (parallel to SERVER_START; SERVER_READY now depends on both)
  • executeCoreStart spawns continuum-core-server (or detects a pre-launched one via socket-alive probe)
  • executeCoreReady polls the Unix socket for accept-readiness with a 30s timeout
  • spawnCoreProcess wires up stdout/stderr forwarding + on('exit') respawn

Layer B — Never give up reconnecting (ORMRustClient.scheduleReconnect)

  • Removed the < 10 cap that left widgets blank permanently after ~3min outage
  • Backoff still exponential (capped exponent at 5 → max 30s delay)
  • Periodic warn every 10th attempt so the log isn't silent

Layer C — Panic-loop detector (in spawnCoreProcess on('exit'))

  • Track restart timestamps in rolling 60s window
  • If >5 restarts in window → STOP + surface error (binary structurally broken; spinning forever wastes CPU)
  • cleanup() sets coreShuttingDown=true BEFORE killing so the handler doesn't interpret SIGTERM as crash + respawn

Paths covered

Path Status
npm start (dev) fixed
scripts/install.sh + CONTINUUM_AUTO_LAUNCH=1 (Carl curl install) fixed (ends with npm start)
bootstrap.sh + curl | bash one-liner fixed (delegates to install.sh)
docker compose up (Carl-docker path) unchanged (JTAG_SKIP_HTTP gate makes orchestrator a no-op; container stack handles it)

Out of scope (separate follow-ups)

  • Layer D — graceful degradation UX (Core offline — showing cached data banner) is widget-side, orthogonal
  • Build(deps): Bump commander from 13.1.0 to 14.0.0 #56 SIGABRT shutdown — that's an upstream Rust issue. This PR ensures the orchestrator can RESTART after such a crash; fixing the SIGABRT itself is its own work.

Validation

  • tsc --noEmit clean (zero new errors)
  • bash -n scripts/install.sh clean
  • Precommit passed
  • Manual repro pending: kill continuum-core-server mid-run → orchestrator respawns + widgets recover within ~3s
  • Carl-case dry-run on a fresh-ish machine (deferred per Joel's "test on Carl path with airc" pattern)

Why it matters strategically

This is Phase 0 of AGENT-BACKBONE-INTEGRATION — the local-fallback story (Codex / Claude Code falling back to local Continuum on rate limits) requires the Rust core to actually be running reliably. Today it's not unless the user knows the manual launch trick. This PR is the prerequisite that makes everything downstream (HTTP shims, capability mesh, training flywheel) buildable on a stable substrate.

🤖 Generated with Claude Code

The all-widgets-blank-on-refresh bug had three compounding causes
captured in continuum#722#issuecomment-4355290646. This commit closes
A + B + C in one PR.

ROOT CAUSES (pre-fix)
=====================

1. continuum-core-server was NEVER auto-spawned by `npm start`.
   parallel-start.sh:203 BUILDS the binary, but no script LAUNCHES it.
   SystemOrchestrator only spawned the TS HTTP/WebSocket server, not the
   Rust core. Users had to manually `./target/release/continuum-core-server &`
   in another tab. The dominant repro: every browser refresh hit a dead
   IPC pool because the core was never running.

   This affected the Carl-case install path too — scripts/install.sh:598
   ends with `npm start` (when CONTINUUM_AUTO_LAUNCH=1), so the Carl
   curl-install flow inherited the same dead-core symptom.

2. ORMRustClient.scheduleReconnect gave up after 10 attempts (~3min).
   Even when the core eventually came back, the IPC pool stayed
   permanently dead with "Gave up reconnecting" — pre-fix the only
   recovery was to restart the entire TS server.

3. No process supervisor. Nothing restarted continuum-core-server when
   it crashed (relevant to #56 SIGABRT). Even if a user did launch it
   manually, a single crash left the system in the same dead state.

LAYER A — SystemOrchestrator owns the Rust core lifecycle
==========================================================

SystemMilestones.ts:
  - New CORE_START + CORE_READY constants
  - SERVER_READY now depends on CORE_READY (so widgets that mount on
    first browser load find a live IPC pool)
  - CORE_START runs in parallel with SERVER_START (different socket /
    process, no contention)
  - MILESTONE_COMPLETION_CRITERIA entries documenting the socket file
    + process-name signals

SystemOrchestrator.ts:
  - executeCoreStart() — spawn the binary OR detect an already-running
    instance (user pre-launched in another tab) via socket-alive probe
  - executeCoreReady() — gate-check by polling the Unix socket for
    accept() readiness, with a 30s timeout
  - resolveCoreBinaryPath() — search src/workers/target/release/ then
    workers/target/release/ then src/workers/target/debug/ (debug as
    dev fallback)
  - findRepoRoot() — walk up CWD to find .git or package.json with the
    right name; orchestrator may be invoked from various CWDs
  - getCoreSocketPath() — canonical socket path (mirror of bindings'
    getContinuumCoreSocketPath() to avoid pulling the bindings module
    here, which has its own initialization order concerns)
  - isCoreSocketAlive() — stat()+isSocket() then connect() probe; both
    needed because a stale socket FILE can outlive its server (kernel
    won't auto-clean)
  - spawnCoreProcess() — spawn with stdout/stderr forwarding +
    on('exit') handler that respawns with exponential backoff

Docker-mode safety: all three new methods early-return when
JTAG_SKIP_HTTP is set (the same env signal the existing executeServerStart
uses to detect "container stack owns this layer, orchestrator should
not duplicate"). The continuum-core container handles the Rust core
in docker mode; orchestrator does nothing.

LAYER B — Never give up reconnecting
====================================

ORMRustClient.ts scheduleReconnect:
  - Removed the `if (this.reconnectAttempts < 10)` cap
  - Backoff still grows exponentially but caps the EXPONENT at 5 (so
    delay is 1s, 2s, 4s, 8s, 16s, 30s, 30s, ... after that)
  - Surfaces a console.warn on attempt 1 + every 10th attempt so the
    log isn't silent during long outages — debugger / user can tell
    whether reconnection is iterating (different errors) or stuck
    (same error). Aligns with CLAUDE.md never-swallow-errors rule.
  - Composes with Layer A: orchestrator respawns the core; IPC pool
    stays ready to reconnect when the new core comes up.

LAYER C — Panic-loop detector (in same on('exit') handler)
==========================================================

Restart-on-crash is layered into spawnCoreProcess's on('exit'):
  - Track restart timestamps in a rolling 60s window
  - If >5 restarts within that window → STOP restarting + surface error
  - The binary is structurally broken (missing dylib, port collision,
    model dir gone, etc); panic-looping consumes CPU + spam without
    ever recovering. Better to fail loud than spin forever.
  - User restarts orchestrator after fixing the underlying issue

The cleanup() method sets coreShuttingDown=true BEFORE killing —
without this the on('exit') handler would interpret the SIGTERM as a
crash and respawn the core during teardown (self-inflicted panic loop).

PATHS COVERED
=============

  - npm start (dev)                       → fixed
  - scripts/install.sh + auto-launch      → fixed (ends with npm start)
  - bootstrap.sh + curl|bash one-liner    → fixed (delegates to install.sh)
  - docker compose up (Carl-docker path)  → unchanged (JTAG_SKIP_HTTP gate)

OUT OF SCOPE
============

Layer D (graceful degradation UX — "Core offline — showing cached data"
banner) is widget-side and orthogonal. Separate PR.

Per #56 SIGABRT shutdown — that's an upstream Rust issue. This PR
ensures the orchestrator can RESTART after such a crash; fixing the
SIGABRT itself is its own work.

VALIDATION
==========

  - tsc --noEmit clean (no new errors in any file)
  - bash -n scripts/install.sh clean
  - Manual repro pending Joel's nod: kill continuum-core-server mid-run,
    confirm orchestrator respawns + widgets recover within ~3s

Closes #722.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
joelteply pushed a commit that referenced this pull request May 1, 2026
…egression + #978 nullish-coalescing cleanup

THREE related changes from a live `npm start` test session 2026-05-01:

1. ALPHA-GAP-ANALYSIS.md is now THE single source of truth
   - Refreshed to 2026-05-01 with live-verified state
   - New "Today's Snapshot" section: what worked + broke in real
     `npm start` from feat/airc-send-command (#977 + #978 + #979 stack)
   - 3 new live-observed bugs in Phase 0:
     · NEW-A: continuum-core-server SIGABRT in vendored llama.cpp
       Metal `llm_build_smallthinker` cleanup. Real stack captured.
     · NEW-B: seed retries 21x/480s before giving up (concrete
       fail-fast fix designed)
     · NEW-C: shared/config.ts has /Users/joelteply/... HARDCODED
       (Carl-blocker)
   - 10 closed-since-Apr-17 items marked DONE
   - 21 new high-numbered open issues catalogued
   - Shortest path to "Install. Talk to AI." spelled out
   - Open PRs (continuum #976 #977 #978 #979 + airc #387) listed
   - Workflow note per Joel 2026-05-01: merge-to-canary, not PR-and-wait
   - Two predecessor docs DELETED + content folded:
     · docs/PRE-ALPHA-GAP-ANALYSIS.md (predates DMR pivot)
     · docs/planning/CARL-AND-DEV-PATH-TO-WORKING.md (interim)

2. SystemMilestones.ts — fix the #977 regression
   Original #977 added CORE_READY as SERVER_READY dep; consequence
   was browser never opens when Rust core SIGABRTs (Joel observed:
   "I don't see a browser"). This commit decouples them — SERVER_READY
   depends only on SERVER_START. SYSTEM_HEALTHY (monitoring signal)
   still requires both. Live-verified: browser opens despite
   SIGABRT-looping core. Joel confirmed: "opened good job."

3. AiLocalInference{Start,Status}ServerCommand.ts — || → ??
   Three nullish-coalescing fixes left uncommitted from PR #978.

NEXT STEPS for the test devices Joel just mentioned:
1. Verify NEW-C path bug repros on fresh test device (it should)
2. File NEW-A + NEW-C as GitHub issues
3. Trace seed-time llm_build_smallthinker call chain — likely a
   Candle-on-chat-hot-path bug per PR891 pivot
4. Implement seed fail-fast (~30 LOC) so install UX doesn't rot 8
   minutes per attempt

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@joelteply
joelteply changed the base branch from main to canary May 1, 2026 16:14
joelteply pushed a commit that referenced this pull request May 1, 2026
… T7)

Live-observed 2026-05-01 from M5 QA-Watcher tab Task 7:

  $ ./jtag airc/send --message="..."
  → stderr: "ERROR: Not initialized
    (/Users/joelteply/Development/cambrian/continuum/src/.airc).
    Run: airc connect"

Root cause: spawn('airc', argv) inherited the daemon's CWD (typically
src/ when invoked via ./jtag). airc's auto-scope rule walks up looking
for a .airc/ — found nothing because src/.airc/ doesn't exist; the
actual scope is at repo-root .airc/.

Fix: belt-and-suspenders so the spawn is unambiguous about which scope
it targets:
  - cwd: <repoRoot>      → airc auto-scopes from continuum's git remote
                            (→ #cambriantech), which IS the desired
                            project-room behavior
  - env: AIRC_HOME=<repoRoot>/.airc  → even if airc's CWD-walk were
                            blocked or modified, AIRC_HOME pins the
                            scope explicitly

Added private static findRepoRoot() — walks up from CWD looking for
.git or package.json with name='continuum'. Mirror of the same method
in SystemOrchestrator (#977). Compression-deferred: when a 2nd
airc-CLI-wrapping command lands (airc/peers, airc/whois, airc/identity/set),
extract a BaseAircCommand with this helper as a protected method per
the file header note.

Verified: tsc --noEmit clean. End-to-end repro of the BUG was the
M5-QA Task 7 broadcast that landed in airc #general (timestamp
2026-05-01T17:03:51Z).

Composes with PR #979 — same outbox feature, different bug surface.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
joelteply pushed a commit that referenced this pull request May 1, 2026
…r session

Live-observed during the chat-with-AIs test session (Joel "you guys
need to all remember to chat with the ais"):

F1 (= existing #75 task): personas reply but with IDENTICAL canned
text regardless of message content. Sent specific questions; got
generic "Hello! I'm here to assist with any code review and analysis
tasks..." back from multiple personas, recursive replies-to-replies.
Cognition pipeline isn't engaging the message — generic-greeting
template fires. THIS is the reason "AI doesn't really talk."

F2 (NEW): ai/local-inference/start reports running:false after core
SIGKILL+respawn. The Anthropic-compat HTTP server is initialized once
via OnceCell at core startup; not re-triggered when core restarts.
External agents pointing ANTHROPIC_BASE_URL would silently break on
any core restart. Important for AGENT-BACKBONE Phase 1 reliability.

F4 (NEW, CRITICAL): TS daemon's IPC client pool unrecoverable after
core SIGKILL+respawn. ./jtag ping HANGS, ./jtag chat/send TIMES OUT.
Sockets exist + accept connections + new core is alive, but commands
don't complete. Full npm stop+start required to recover. THIS IS THE
CARL-KILLER — every NEW-A SIGABRT in the wild puts users in this
state.

F4 supersedes the "#977 closes #722" claim. #977 Layer B (unlimited
reconnect) gets the SOCKET back but the REQUEST PIPELINE is wedged.
Three fix paths proposed in the doc:
  1. Drain pending requests with "core restarted, reissue" error
     before reconnecting (so callers can retry)
  2. Refuse new requests until pool cleanly drained
  3. Re-create entire pool on detected core restart

Composes with Task 8 supervisor-doesn't-own-pre-existing-cores: even
when supervisor adopts an inherited core, IPC layer needs to handle
"core changed under us" event. F4 is true regardless of who spawned
the core.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
joelteply pushed a commit that referenced this pull request May 1, 2026
…ia PID watcher

M5-QA Task 8 (live-observed 2026-05-01) caught this:

  $ pgrep -x continuum-core-server  # PID 67115 (alive 1h24m)
  $ kill -9 67115                   # simulate SIGABRT
  $ sleep 30
  $ pgrep -x continuum-core-server  # NONE — supervisor never respawned

Root cause: when parallel-start.sh's Phase 3 spawn beats orchestrator's
executeCoreStart to it, executeCoreStart's isCoreSocketAlive() check
correctly detects the existing core + skips the spawn. But this means
this.coreProcess stays null + no on('exit') handler is attached.
When the inherited core dies (NEW-A SIGABRT, kill -9, anything), the
supervisor is BLIND to the death → no respawn.

The original #977 design assumed the orchestrator OWNED the spawn.
parallel-start.sh independently spawning continuum-core-server (since
it predates this PR) breaks that assumption.

THIS FIX (Task 8 layer):

When isCoreSocketAlive=true at orchestrator start, attach a PID-poll
watcher (`process.kill(pid, 0)` every 2s) on the inherited core's PID.
When the watcher detects the PID is gone, spawnCoreProcess() is called
to bring up a managed replacement — and from that point on, the normal
on('exit') handler from spawnCoreProcess takes over the lifecycle.

So the lifecycle transitions are:
  parallel-start.sh spawns core    →  orchestrator finds it via socket-alive
                                  →  adoptInheritedCore registers PID-poll
                                  →  inherited core dies (SIGABRT/kill)
                                  →  watcher fires + spawnCoreProcess()
                                  →  managed replacement now in this.coreProcess
                                  →  normal supervisor path takes over

API additions:
  - State: adoptedCorePid (number|null), adoptedCoreWatcher (interval handle)
  - Constant: ADOPTED_CORE_POLL_MS = 2_000
  - Method: adoptInheritedCore(corePath, socketPath)
  - Method: findCoreProcessPid() — pgrep -x continuum-core-server
  - Method: stopAdoptedCoreWatcher() — idempotent cleanup
  - cleanup() now stops the adopted-core watcher first

Failure-loud surface: if findCoreProcessPid() returns 0 (pgrep can't
find it OR doesn't exist), we log a warn explaining the supervisor
will be blind to the inherited core's death + return without crashing.
Same intent as the never-swallow-errors rule — the gap is real, we
surface it rather than pretend.

What this STILL doesn't fix (separate scope):

F4 (the carl-killer): TS daemon's IPC client pool can't recover even
when supervisor respawns the core. Sockets reconnect but the request
pipeline stays wedged. Fix is in ORMRustClient.ts (drain pending +
reissue, OR refuse new until drained, OR recreate pool). Tracked in
gap analysis under F4.

F2 (local-inference HTTP server doesn't re-bind on core restart):
when a managed replacement spawns, ai/local-inference/start needs to
be re-triggered. Hooked off this fix's spawn callback in a follow-up.

VALIDATION:
  - tsc --noEmit clean across the repo
  - Live deploy-test deferred since system is currently wedged from
    the SIGKILL test that surfaced T8 in the first place; will
    validate after npm stop+start (which the dev tab can trigger
    when ready)

Composes with #977's existing supervisor + the dep-graph fix from
ecb0eed. Closes part of #722 + the M5-QA T8 finding.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@joelteply
joelteply merged commit d778262 into canary May 1, 2026
4 checks passed
@joelteply
joelteply deleted the fix/722-rust-core-supervisor branch May 1, 2026 20:19
joelteply added a commit that referenced this pull request May 2, 2026
#1010)

When WSL2 has lost external network reachability (vEthernet / HNS
corruption is common on Win10/11 after sleep cycles, driver updates,
or system patches), the curl inside `bootstrap.sh | bash` takes 30+
seconds to time out with a cryptic error — and the user has no signal
that the issue is environmental, not continuum-related.

Caught live 2026-05-02 by continuum-b69f during Carl-OOTB Windows
testing (issue #1006). After PR #1005 fixed the WSL detection bug,
install.ps1 delegated into bootstrap.sh successfully — and the WSL-
side curl just hung. The user has no way to tell whether the install
is broken or their box's WSL is broken.

Fix: 5s curl probe to raw.githubusercontent.com from inside WSL
BEFORE the delegate. If it fails, surface explicit Windows-side
remediation:
  1. wsl --shutdown
  2. (as admin) Restart-Service hns -Force
  3. Reboot Windows
  4. Edit %USERPROFILE%\.wslconfig — networkingMode=NAT
  + Re-run command

Pattern: same family as install.sh's friendly-failure phase traps
(#977 work) — fail loudly and tell the user exactly what to try
NEXT, instead of dying silent or with a 30s mystery timeout.

## Tests

- Edit-only PowerShell change, no shape change to delegate path
  when probe passes.
- Linux/Mac CI not affected (probe block is inside install.ps1).
- Live validation pending b69f's box (currently the WSL2 NAT is
  broken on their box per #1006 — perfect natural test case for
  the new probe message).

Co-authored-by: Test <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
joelteply pushed a commit to RebelTechPro/continuum that referenced this pull request May 13, 2026
… outbox + dev-tooling

Phase 2.5 of AGENT-BACKBONE-INTEGRATION (CambrianTech#976 §11.2) — outbox direction
of the bidirectional persona ↔ external-agent flow tracked under
continuum#967. Personas (and any other Continuum caller) can now publish
to the cross-machine peer mesh that humans + Claude Code + Codex tabs
share, via the universal Commands.execute() primitive:

  const { delivered, channel, stderr } = await Commands.execute(
    'airc/send',
    { message: 'Helper AI here — building on top of CambrianTech#978' },
  );

WHAT'S ADDED
============

  src/generator/specs/airc-send.json
  src/commands/airc/send/  (full module: shared types, server, browser,
                             tests, README, package.json)

WIRE BEHAVIOR
=============

  - explicit params.channel       → that channel
  - omitted                       → airc auto-scopes (cwd's git org)
  - params.peer provided          → addressed DM (`airc send @<peer> <body>`)
  - params.peer omitted           → broadcast to channel

  result.delivered=true means airc CLI exited 0 — handed off to the
  substrate (which may queue per airc#381 layer B). result.stderr
  surfaces airc's own [QUEUED] / [GONE] / [RATE-LIMITED] markers so
  callers can react to substrate signals rather than treating them as
  silent.

NOT IN V0 (out of scope, deferred)
===================================

  - Inbox direction (airc → persona inbox) — needs an embedded
    `airc connect` Monitor process tree; tracked under continuum#967
    as v0.5
  - AircBridge module that auto-spawns per-persona airc identities —
    abstraction value emerges only when 2+ airc CLI wrappers exist;
    deferred per CLAUDE.md compression principle (don't extract before
    pattern is real)
  - channelPrefix / caller-identity helper — original spec had it but
    JTAGContext has no `personaName` field; synthesizing one via
    inline cast was a typing smell of the same class as CambrianTech#978 cleaned
    up. Callers format their own message body — more truth-typed.
  - openai_compat.rs symmetry — Phase 1 §4.1, separate scope

DESIGN NOTES (compression-deferred)
====================================

When the 2nd airc-CLI-wrapping command lands, extract `BaseAircCommand`
with protected `invokeAirc(argv): Promise<AircCliResult>` so spawn +
stdout/stderr capture + ENOENT-detection logic isn't duplicated.
Premature now (one command isn't a pattern); annotated in the file
header for future-me to find.

VALIDATION
==========

  - tsc --noEmit clean across the repo (0 errors, 0 new)
  - eslint clean on staged files (0 errors)
  - Eslint baseline bumped 6255 → 6257 (2 parse errors on the test
    files generator emitted for this command, same pre-existing class
    every command's test files exhibit)
  - Manual repro deferred until M1 Carl-test bed exercise

Composes with CambrianTech#976 (design doc), CambrianTech#977 (Rust core supervisor), CambrianTech#978
(local-inference commands), airc#387 (substrate reliability under
the sends this command emits).

Closes part of continuum#967 (outbox direction).

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