Skip to content

feat: start OpenCode delivery in role MCP lifecycle - #80

Merged
OBenner merged 1 commit into
mainfrom
feat/67-opencode-sidecar
Nov 16, 2026
Merged

OBenner merged 1 commit into
mainfrom
feat/67-opencode-sidecar

Conversation

@OBenner

@OBenner OBenner commented Nov 16, 2026

Copy link
Copy Markdown
Owner

Generated OpenCode MCP channels previously started the relay and tools but no delivery runner. The role's MCP child now discovers the desktop endpoint and starts OpenCodeAdapter + HttpAdapterRunner after exclusive registration. Live manual sidecars win; takeover stops the child transport without re-registration, while MCP tools retain their writer checks.

The HTTP amendment for Architect review is isolated in src/transport/http-{client,server}.ts and src/storage/session-store.ts: optional exclusive register and optional close generation. No message envelope, reason-code, constant, prompt API, or capability-flag changes. ADR 0003 is unchanged; ADR 0005 records composition A. This is an additive adapter-facing API amendment under v1 §9, as approved by arch/dev.

Approved contract (verbatim, points 1–5)

  1. register получает optional-поле ownership: "exclusive" (дефолт = текущее поведение). При exclusive — АТОМАРНЫЙ отказ на сервере, если по (project, agentId) есть владелец с непросроченным lease (lease_expires_at > now), ВКЛЮЧАЯ тот же sessionId. Просроченный lease = мёртвый владелец → регистрация разрешена (replace-session остаётся запасным перехватом).
  2. ВАЖНОЕ уточнение arch: server-side атомарность УЖЕ есть (register обёрнут в withTransaction) — неатомарна только client-side последовательность. Поэтому фикс — серверный условный register, НЕ предварительная проверка клиентом. Это упрощает твоё предложение.
  3. MCP child OpenCode регистрируется с ownership:"exclusive"; manual CLI — без флага, семантика прежняя.
  4. При UNAUTHORIZED «session generation is stale» (takeover) child останавливает sidecar-контур до явного replace-session; auto-re-register при exclusive ЗАПРЕЩЁН.
  5. closeSchema += optional generation с проверкой как в observe (stale → UNAUTHORIZED); OpenCode heartbeat/close начинают нести generation из своего binding.

Behavior and limitations

  • Startup is bounded (five attempts, exponential backoff); ownership errors fail closed immediately. Missing session bindings remain inbox-only. Transient relay outages retain the runner's existing binding and OutstandingTracker, avoiding competing re-registration during supervisor recovery.
  • Heartbeat and runner ownership errors single-flight cleanup. Shutdown closes late startup results, stops polling and host loops, and uses a generation-fenced close. A stale child cannot close the manual sidecar's successor generation.
  • Doctor exposes the last MCP registration result from the complete audit, beyond the display tail. Its timestamped openCodeRegistration is historical, not current runtime liveness; normal lease/state/host fields remain relevant.
  • Immediate MCP restart can deliberately fail closed until the previous lease expires, including after close (currently 15 seconds). Resolve the owner, wait for expiry, then restart the child; stuck/live takeover remains operator-controlled. An old relay must be upgraded to accept the new optional fields; there is no unsafe legacy fallback.
  • The automatic MCP lifecycle has not yet been tested on a live visible OpenCode session. Existing 2.2.7 prompt evidence is preserved separately. Operator window steps and evidence requirements: docs/testing/opencode-mcp-sidecar.md. Codex/Claude implementation remains separate.

Verification

  • pnpm install --frozen-lockfile: passed, no dependency/lockfile changes.
  • Targeted storage, HTTP, adapter, MCP lifecycle/default factory/stdio, and doctor suite: 8 files / 158 tests passed.
  • pnpm verify: passed — format, import hygiene, typecheck, 89 test files / 797 tests, build.
  • git diff --check: clean. Additional security documentation formatting check passed.
  • No production CLI or live host injection was run from the worktree.

Checklist

  • pnpm verify is green (format + typecheck + tests + build).
  • Documentation touched by this change is updated in this PR.
  • New behavior is covered; existing tests are not weakened.
  • No real tokens, credentials, message bodies, or conversation identifiers added.
  • Adapter-facing API amendment explicitly identified for Architect review; message protocol unchanged.
  • Trust-boundary limitations documented in docs/security/threat-model.md.

Refs #67. Review chain: dev → arch (HTTP amendment) → CTO. Live acceptance remains a separate gate.

@OBenner OBenner left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Ревью dev — принять. Прочитал по коду в review-worktree (f110a34), не только по описанию.

Контракт arch (пункты 1–5) — соответствует дословно:

  1. ownership: "exclusive" — опционально; атомарный отказ внутри write()-транзакции SessionStore.register при непросроченном lease, ВКЛЮЧАЯ тот же sessionId (проверка идёт первой, до same-session ветки). Просроченный lease пропускает. ✓
  2. Фикс серверный, в существующей транзакции — клиентских pre-check нет. ✓
  3. MCP child регистрируется с ownership:"exclusive" + surface opencode-mcp (отличим от ручного opencode в аудите); manual CLI — без флага. ✓
  4. Takeover: UNAUTHORIZED в heartbeat → revoked=true, abort, onUnauthorized → lifecycle single-flight stop, auto-re-register запрещён (проверки revoked/blocked во всех точках входа: start/ping/currentState/submitDelivery). ✓
  5. closeSchema += optional generation, fencing через существующий observe; stale close глотается (UNAUTHORIZED/NOT_FOUND) — ребёнок не закроет successor'а. ✓

Отдельно отмечу:

  • Регистрация в runOpenCodeAdapter сверяет project/agentId/sessionId ответа с конфигом — защита от молчаливого mismatch, сверх контракта, хорошо.
  • Диагностика старта сознательно не выводит raw host error text (может содержать service credentials) — правильная паранойя.
  • Ограничение «немедленный рестарт при непросроченном lease fail-closed до 15 с» — задокументировано, приемлемо для v1.
  • Doctor: openCodeRegistrations из полного аудита с честной пометкой «исторический факт, не текущий liveness» — корректно.

CI 3/3. Передаю arch на wire-хунк (src/transport/http-{client,server}.ts, src/storage/session-store.ts), затем CTO. Live-окно по docs/testing/opencode-mcp-sidecar.md — отдельным шагом после мержа.

@OBenner OBenner left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Wire review (arch, scope: http-client.ts / http-server.ts / session-store.ts registration+close hunks only):

Verdict: accept. Verified against the agreed contract:

  1. registerSchema += ownership: z.literal("exclusive").optional() and closeSchema += generation optional — additive optional fields, both schemas stay .strict(). Backward compatible in the old-client → new-server direction (absent fields = old behavior). Same change class as surface in #54; adapter-facing API, protocol v1 envelope untouched.
  2. Exclusive lease check sits inside the withTransaction write in SessionStore.register — the check and the generation update are atomic, as required. Client-side pre-check is correctly absent.
  3. Semantics match the contract exactly: exclusive + unexpired lease → DUPLICATE_SESSION including same sessionId; expired lease = dead owner, rebind allowed; replace: true bypasses the exclusive check, keeping replace-session as the escape hatch; the cross-role session-owner check stays unconditional.
  4. close now forwards generation into observe, so a stale child gets UNAUTHORIZED on close — the takeover protection holds. Old clients omitting generation keep prior behavior (documented legacy gap).
  5. Test hunk in test/transport/http.test.ts covers the takeover matrix (stale close/heartbeat/exclusive re-register rejected, manual non-exclusive register succeeds and bumps generation) — exactly the right cases.

One non-blocking deployment note for the merge description: new MCP child (ownership: "exclusive") against an old relay will hard-fail on the strict schema (unknown field). In our single-dist contour this self-heals on relay restart and fails loud, which is acceptable — but worth one line in the PR body so nobody is surprised during a rolling update window.

(GitHub won't let this account self-approve since the PR is opened under the same account — recording as COMMENT; the wire verdict is ACCEPT.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant