Skip to content

feat(mecatui): enforce API compatibility before startup - #2269

Merged
jbeda merged 2 commits into
mainfrom
impl/2117-remote-compatibility
Oct 12, 2026
Merged

jbeda merged 2 commits into
mainfrom
impl/2117-remote-compatibility

Conversation

@jbeda

@jbeda jbeda commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Scope

First standalone PR in the extraction of #2239. Check the existing API-major descriptor before mecatui accesses a session or starts the normal UI, including resume and reconnect.

  • Give directional client/server update advice; distinguish invalid descriptors, authentication, connection failures, and timeouts.
  • Keep compatibility probes authenticated and free of session-affinity headers.
  • Close failed-startup resources and retire signal ownership before recovery; preserve two-signal shutdown behavior.
  • Align TypeScript SDK diagnostics without changing its public error shape or retry behavior.

Most added lines are offline regression tests; the production changes stay at client/startup boundaries.

API compatibility

Backward-compatible: API major remains 1. The existing compatibility descriptor, feature identifiers, and capability advertisements keep their meaning; this PR enforces the declared major rather than changing the protocol. No required-feature floor, schema change, stored-data migration, or tool-call identity change is introduced. No server upgrade is required for existing API-major-1 servers with compatibility discovery; servers below that discovery floor are refused with update advice.

Contributor guidance uses feature identifiers rather than a negotiated minor version. Root and path-scoped instructions require agents to surface proposed breaking changes and upgrade implications to the operator for explicit approval before implementation. Wire-affecting PR descriptions must record the compatibility assessment; plans record it when used, but are optional.

PR sequence

  1. Remote compatibility preflight (this PR).
  2. Canonical typed Mecatl ToolCallID and provider replay separation, preserving stored data.
  3. Typed hook lifecycle/correlation contract and recovery.
  4. TUI hook correlation and presentation.

#2239 remains frozen/draft at cac37575e8cd3b09c0a3893abf53aa47bd208003, retained as the extraction reference.

Verification

  • task test
  • task test:race
  • task lint
  • task docs
  • task sdk:lint, task sdk:typecheck, task sdk:test
  • go run ./cmd/mecademo: actual tool call, permission ask/approval, and result
  • Four-axis implementation review with affected delta rechecks: no remaining findings

All passed locally. Tests are offline and isolated; host UNIX-socket tests used short system temporary paths because managed lease paths exceed the socket address limit. Full-suite verification caught and fixed a gRPC deadline/local-context observability race, with deterministic regression coverage.

Draft for human review. Later identity/hook/TUI slices are not implemented here.

Archived implementation plan and PR sequence.

@jbeda

jbeda commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor Author

Implementation plan archive — remote compatibility preflight

  • Slug: 2117-remote-compatibility
  • Source path (local provenance): .scratch/2117-remote-compatibility-plan.md
  • Branch: impl/2117-remote-compatibility; base: main
  • Immutable branch start: c6d7338888b94935b67535a0bd37902dd944ff71
  • Verified PR head: 19dc5f945919cb81c5f74dbaddcafe269460c85a
  • Updated: 2026-10-12T19:19:32Z
  • SHA-256 of the full plan portion below: 2e07ddb0f7eb042848be660f46409c85be889388db96c3c52c65e15d36cd8c5f

The preflight slice is implemented and locally verified. The operator approved a
follow-up documentation/context amendment: keep feature identifiers, document
major-bump criteria, require explicit operator awareness/approval of breaks, and
record the assessment in wire-affecting PR descriptions. Plans are optional.
This amendment passed documentation checks and focused independent review; it
changes no runtime behavior or API version. Original runtime gates remain valid.
Later identity, hook, and TUI slices remain deferred. Scratch paths are provenance,
not remotely accessible links. No sensitive content was omitted.


Remote compatibility preflight and PR extraction sequence

Slug: 2117-remote-compatibility
Implementation branch: impl/2117-remote-compatibility
Base branch: main

Implementation authorized by Joe on 2026-10-10 and completed. Verification and
panel receipts are recorded in .scratch/2117-remote-compatibility/run.md.
Requirements/tasks below retain the reviewed scope; later PRs remain deferred.
Branch start: c6d7338.

Goal and boundaries

Deliver an independently useful first PR: mecatui checks the existing remote
wire contract before startup proceeds and gives directional update guidance.
Reuse GetCompatibilityInfo; do not invent a second version protocol or compare
application semver. Keep this small: one preflight, existing auth/recovery paths,
focused transport/startup tests, and matching SDK error wording.

No identity migration, hook envelope/recovery, TUI hook presentation, persistence
redesign, rolling-upgrade framework, supported-major ranges, or new server RPCs.
Do not bump api_major in this PR. Missing optional features do not block startup.

Approved compatibility-policy amendment

Joe approved adding contributor context and updating this PR's description:
retain major-plus-feature negotiation without a minor version; document breaking
wire changes and upgrade coordination in docs/architecture/api-surface.md; add a
root AGENTS.md reminder and .claude/rules/wire-api-compatibility.md across producer
and client paths. Agents must surface a proposed break and obtain explicit
operator approval before implementing it or bumping the major. Wire-affecting PR
descriptions must carry the compatibility assessment; plans record it only when
used. This amendment changes guidance, not runtime behavior or API versions.

Frozen reference and delivery sequence

Leave branch impl/2117-tool-hook-correlation and PR #2239 untouched at
cac3757. Extraction baseline is
599bf01. These are reference artifacts, not the
implementation base. Preserve accumulated feedback in
.scratch/2117-tool-hook-correlation/pr-review-feedback.md.

The new work consists of four useful PRs, each with its own tests/docs:

  1. Remote compatibility preflight (this detailed plan): existing advertised
    major is enforced before create/resume; clear update-client/server guidance.
  2. Canonical tool-call identity: Mecatl ToolCallID becomes the globally unique
    primary identity; ProviderToolCallID and other touched identity references are
    distinct named Go types. Separate LLM DTOs from domain calls/results; retain
    opaque durable replay metadata atomically with Session, without a new store.
    Include canonical execution/approval/authorization/delegation/hook/audit/learning
    semantics and necessary mechanical host/provider updates. No hook revision
    feature or new presentation. Deliberate breaking Go APIs are approved; new code
    must preserve/read existing stored data and pending state. No downgrade guarantee.
  3. Hook lifecycle contract: typed hook/review identities, revision and explicit
    origin, publication admission/recovery, receipts/details and legacy review
    continuation, plus server wire projections. No new TUI layout.
  4. TUI correlation: canonical hook store, scrollback association, stale/conflict
    handling, details/approval/rendering/cache integration, with the first three
    layers supplying settled contracts.

Plan each later PR in its own ignored plan after the preceding contracts settle.
Do not give a subagent the whole identity migration. PR2 task frontier must include
separate tasks for shared types; turn conversion; each of the three real providers;
snapshot decoding; pending continuations; event reconstruction; execution/results;
delegation; learning/evidence; hook/audit inputs; host projections; replay lifecycle.
Split further when a task contains two independent integration boundaries.

Create the first branch from main only during approved plan-implement execution.
Record its actual start OID then; do not use the frozen feature branch as base.
Before creation, refresh/verify origin/main and confirm any material differences
from the researched baseline; never move/reset the frozen branch. Local origin/main
was c6d7338 during research, not freshly fetched.
The touched preflight/SDK production files were unchanged between original
baseline, frozen head and that origin/main. Keep the active implementation branch
in this checkout root for human review once implementation begins, with the frozen
branch still retaining the reference commit.

Open/push/commit actions require explicit authority; planning grants none. Later
PRs target their predecessor when stacked, each layer builds independently, and
humans alone merge. Do not force-push/close/repurpose #2239 without separate approval.
A final assembled-stack comparison against the frozen implementation must account
for reused behavior, approved redesigns and intentionally deferred scope.

Current behavior

  • Proto GetCompatibilityInfoResponse provides api_major, supported feature IDs and
    operator-enabled capabilities; these answer separate questions
    (contracts/proto/mecatl/v1/harness.proto:662).
  • Server APIMajor=1, shared by gRPC and GET /v1/compatibility
    (internal/adapter/server/features.go:3; http.go:2027).
  • Mecatui Dial is lazy. Startup calls startupResumeConfig/loadExactStartupResume
    immediately after Dial, before constructing the UI (cmd/mecatui/main.go:286-300).
  • Client compatibilityCapabilities reads the descriptor but discards major and
    features (cmd/mecatui/client/client.go:470). GetSession can suppress compatibility
    failure for legacy capability fallback (client/session.go:126).
  • TypeScript raw client already performs a headerless/session-independent preflight
    before operations and rejects an unequal major; its error is not directional
    (sdk/typescript/src/raw.ts:195-269). Preserve its generation/retry behavior.

Material contracts

Compatibility: support major 1 exactly in this PR. Keep client support independent
of the server build constant: changing the server constant must not silently teach
an old client to accept a new protocol. Equal supported major succeeds regardless
of disabled operator capabilities or unknown additive feature IDs.

Mismatch diagnostics: a positive higher server major identifies an outdated
client and says to update mecatui (SDK: update the SDK). A positive lower major
identifies an outdated server and says to update the server. Missing descriptor
(Unimplemented; HTTP SDK 404) means below the compatibility floor and says update
the server. Include expected/observed majors where meaningful. Zero/negative major
or absent/malformed successful response is invalid compatibility information,
not evidence for an upgrade direction. Keep auth/permission/transport/timeout
failures distinct and preserve their wrapped causes/status. Do not expose tokens,
auth headers or raw connection secrets in diagnostics.

Ordering: after successful Dial, compatibility completes before startup resume
selection (including automatic and auth-recovery candidates), session/model
inspection, session creation, or Tea UI construction. Local embedded startup uses
the same preflight after its server is running; this does not prohibit the local
startup/configuration work needed to start that server. /connect reconnect/restart
must pass the same gate for the new connection. Existing unavailable/optional
capability fallback never converts a startup incompatibility into success.

Networking/lifetime: use a bounded startup RPC (10-second maximum, earlier
caller cancellation/deadline wins), with normal credentials/TLS and no session
routing header. No background probe or new retry loop. On preflight failure close
the client and release transport-owned embedded resources, then retire that run's
signal-handler ownership before returning or recursively entering recovery. Reuse
runCleanup's established ordering: keep second-signal hard-exit active during
cleanup, retire it only afterward (cmd/mecatui/main.go:847-903). Capture actual
startup interruption before retiring the owner, including first signals received
during cleanup: handler retirement itself cancels its context, so checking that
context afterward must not relabel mismatch/timeout as operator cancellation.
Do not merely copy
the current resume-error path, which leaves its signal owner alive. Auth failures
must continue into existing authentication recovery where applicable; never
classify them as upgrade problems or suppress them as an opportunistic resume
failure. Compatibility data reflects the connection, not a session/global cache.
Do not freeze dynamic operator capabilities at startup; existing capability
lookups remain authoritative.

At the preflight error boundary, if its bounded context is canceled/expired,
preserve that context error even if credential refresh returned a closed auth
sentinel instead. Keep raw OAuth responses secret-safe and do not redesign token
refresh (client/client.go:217; internal/adapter/clientauth/oidc.go:367-386).
An expired probe deadline is a timeout; cancellation of the enclosing startup
exits instead of opening another disconnected recovery UI.

/connect's outer restartFromConnectIntentWith currently replaces all errors with
generic recovery text and carries the preceding action's auth reason
(cmd/mecatui/main.go:727-729). Forward only safe client-authored typed compatibility
diagnostics into its existing disconnected overlay, clearing stale auth semantics
for non-auth failures. Do not forward arbitrary server error text. Preserve auth
recovery classification, and return caller cancellation without reopening recovery.
Test the outer wrapper's displayed diagnostic, not just gate rejection.

Types: use a small named client-side API-major type and typed safe compatibility
errors so the outer wrapper can distinguish update advice/invalid descriptors from
untrusted remote errors; avoid generic version strings, a new general
compatibility framework, or changes to generated protobuf numeric fields. Retain
TypeScript's existing IncompatibleServerError shape/class and transport/cause
behavior; only give it directional diagnostics. No new public SDK error fields.

Versions: Go API source versions, remote wire major/features, and persisted
representation versions are independent. PR2 must assess the actual opaque-ID wire
contract and decide explicitly whether changing ID semantics is compatible or
requires a wire-major change. Do not silently prescribe a bump merely for a Go
rename, or assume unchanged protobuf tags prove semantic compatibility. Old clients
without preflight cannot be retroactively fixed by this client PR; any genuine
wire break must account for that in the later plan. Stored-data migration must not
reinterpret historical provider IDs as new canonical IDs or rewrite immutable
learning-evidence bindings without a compatible reader.

Observable acceptance

  • A major-1 fake server receives compatibility first, then normal fresh/resume
    startup proceeds. Unknown extra features and disabled optional capabilities pass.
  • Newer/older major and missing descriptor produce the correct advice; invalid
    descriptor, auth denial, unavailable connection, timeout and cancellation remain
    distinguishable. Positive mismatch examples are exercised with an injectable
    supported-major comparison, not by changing production major 1.
  • Rejected fresh, explicit-resume, automatic-resume and auth-recovery candidates
    send no session inspection/create/resume/mutation RPC and never enter the normal
    UI. A reconnect to a mismatched target is similarly rejected.
  • Real credential/session-affinity fixtures verify the preflight retains normal
    credentials but removes session affinity; no credential values reach errors.
  • A failed embedded/remote startup releases owned connections/resources and retires
    its signal owner after cleanup before recovery/restart. Test failure followed by
    reconnect/interruption with no stale handler; retain second-signal-during-cleanup
    semantics. Auth recovery's disconnected UI remains separate from normal UI.
  • Cancellation/timeout during blocked token acquisition or offline OAuth refresh
    retains context classification without exposing raw OAuth errors. Caller cancel
    exits; /connect does not reopen recovery. Successful reauthentication followed
    by incompatibility displays update advice without a stale session-expired reason.
  • TypeScript gRPC and HTTP/SSE operation paths retain preflight-before-operation
    behavior with directional errors. Auth/network errors retain their class; a
    failed preflight remains retryable under existing generation semantics.

Bite-sized implementation tasks

Tasks are serial/direct-write by default; independent read-only checks may fan out.
Each task has narrow ownership, known paths, and focused tests; never pass the
whole plan as an instruction to implement everything.

  1. Client comparison/diagnostics — client compatibility helper and new focused
    test file. Named major + safe typed compatibility errors and bounded preflight
    using GetCompatibilityInfo/withoutSessionAffinity. Test equal/newer/older/
    invalid/absent descriptors, unknown features, status and header behavior.
    Done when focused comparison/RPC tests pass. No startup/SDK edits yet.
  2. Credential-time cancellation — preflight error handling plus focused blocking
    TokenSource and offline refresh fixtures. Preserve the probe context error when
    credential acquisition masks it; retain secret-safe errors otherwise. Done when
    cancellation/deadline classification survives the real credential interceptor.
    No token-store redesign; depends on task 1.
  3. Startup gate and ownership — main.go after Dial and before resume/UI. Reuse
    cleanup/auth-recovery seams with signal retirement after cleanup, before re-entry.
    Caller-level fresh/explicit-resume tests prove no downstream RPC/UI work on
    rejection and positive success. Depends on 1-2; done when focused tests pass.
  4. Reconnect diagnosis/cancellation — restartFromConnectIntentWith and focused
    connect tests. Safe typed advice reaches existing overlay; clear stale auth
    reason; caller cancel returns instead of recovery. Cover successful reauth then
    incompatible server. No arbitrary remote text projection. Depends on 1 and 3;
    done when outer-wrapper behavior, not just checker output, is verified.
  5. Resume/embedded lifecycle proof — offline automatic/auth-recovery resume,
    embedded positive and rejected-startup cleanup tests. Prove signal owner retires
    before a successor run; retain second-signal behavior during cleanup using the
    existing signal test seams/subprocess fixtures. No real operator environment or
    nondeterministic sleeps. Depends on 3-4; done when affected startup/connect suites
    pass with positive controls and negative cleanup/ordering controls.
  6. SDK directional errors — raw.ts and compatibility.test.ts, existing error
    class/generation logic unchanged. Higher/lower/absent/invalid, both gRPC and HTTP
    unary/stream, auth/network preservation/retry. Done when focused Vitest,
    typecheck and lint pass. Independent of Go tasks after contracts are settled.
  7. Concise documentation — tech-writer for owning remote-servers/troubleshooting
    section; canonical grpc/http reference and docs/architecture/api-surface.md only
    where needed. No repeated displayed advice/common-sense TUI detail. Depends on
    behavior integration; done when docs match actual callers and task docs passes.
  8. Lead integration/gates — run complete checks, panel-review and fix/recheck
    findings. Do not delegate the entire gate/fix loop or combine it with a large
    implementation task. Complete PR must be useful/buildable alone.

Each delegation gets the settled contract excerpt and only its relevant task/files.
If a task discovers an unresolved material behavior, stop and return to planning;
do not delegate that decision to the worker. Intermediate task commits need not
be independently shippable, but the complete PR must build and be useful alone.

Verification and review

Use isolated offline fixtures and test-owned HOME/XDG/UserModelDir paths. No live
providers, real auth state, or operator stores. Prefer existing startup isolation
helpers and poisoned ambient-state negative controls where composition is involved.
Tests assert behavior and ordering, not source-text matches or arbitrary prose.

Focused Go commands: go test ./cmd/mecatui/client and go test ./cmd/mecatui with
-run narrowed to new compatibility and affected startup/connect tests while iterating.
Focused SDK: in sdk/typescript, pnpm exec vitest run test/compatibility.test.ts.
Integrated SDK: task sdk:lint, task sdk:typecheck, task sdk:test (dependencies from
frozen lockfile; report availability blockers rather than claim gates passed).
Lead runs task test once for the integrated change, task lint and task test:race
with 600-second timeouts, task docs for Markdown, and go run ./cmd/mecademo proving
tool call, permission ask/approval and result. Build via task build if needed.
No protobuf changes are expected; if required, revisit scope and regenerate only
via task generate. No new engine export is expected; later identity PR owns API
snapshots/changelog/standalone gates.

Initial implementation panel-review uses the actual recorded branch-start OID,
not moving main or the frozen feature head. Fixes get targeted delta review against
the last reviewed candidate; no unsolicited rebase. Retain publishable plan in a
single verified PR comment under plan-implement once PR publication is authorized.
No commit, push, PR creation/comment or merge is authorized by this planning step.

Decisions and review status

Operator approved: deliberate Go breaks without stored-data loss; opaque durable
session replay without persistence redesign; forward-reading stored-data
compatibility without downgrade guarantee; separate preflight PR ahead of identity;
small pragmatic scope since few deployments are likely caught mid-transition.

No open behavioral choice blocks this first PR. Later identity wire-major policy
and exact legacy migration contracts remain explicitly deferred to PR2 planning.
Fresh-context plan-review plus security check completed; amended startup ownership,
outer /connect diagnostics and credential-time cancellation contracts were rechecked
with no remaining blocker/important gap. Final advisory about cleanup-induced
context cancellation was incorporated explicitly. Reviews used inlined design and
amendments because ignored files are absent from child checkouts; no runtime gates
ran. Receipts: .scratch/2117-tool-call-identity/preflight-plan-review.md.

@jbeda
jbeda marked this pull request as ready for review October 12, 2026 21:14
@jbeda
jbeda merged commit 2fbdea1 into main Oct 12, 2026
66 checks passed
@jbeda
jbeda deleted the impl/2117-remote-compatibility branch October 12, 2026 21:59
This was referenced Oct 13, 2026
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