Skip to content

feat: credential re-read self-heal and relative projectRoot in generated configs (UX 2) - #99

Merged
OBenner merged 2 commits into
mainfrom
feat/ux-repair-relative-paths
Nov 16, 2026
Merged

OBenner merged 2 commits into
mainfrom
feat/ux-repair-relative-paths

Conversation

@OBenner

@OBenner OBenner commented Nov 16, 2026

Copy link
Copy Markdown
Owner

Контекст

Вторая половина UX-задачи (после #93): (a) восстановление после 401/перевыпуска токена без рестарта хост-процесса; (b) убрать оставшиеся абсолютные пути из генерируемых конфигов. Решения согласованы с dev (тред 53aef786/4faf2b04): D1 — per-request чтение с last-good fallback; D2 — relative с absolute fallback, миграция не нужна.

Коммит 1: 55e0802 — credential re-read self-heal

Проблема: MCP stdio-мост читал токен один раз при старте. После rotate-token / doctor --repair работающий канал крутил 401 до рестарта процесса хоста — recovery-loop перерегистрировал сессию с тем же протухшим токеном из памяти.

Фикс:

  • createTokenFileProvider(path, initial) в credentials.ts: перечитывает credential-файл на каждый запрос (RelayHttpClient уже спрашивает провайдер per-call). Перевыпуск действует со следующего запроса, без рестарта.
  • Fallback по уточнению dev: ошибка чтения (ENOENT, Windows sharing violation, torn rename) или пустой файл (mid-rewrite) → последний успешно прочитанный токен; живой канал не роняется.
  • EnsureRelayOptions.token: string | TokenProvider — строка оборачивается (обратная совместимость), probe использует тот же провайдер.
  • Маскирование в diagnostics: все когда-либо выданные токены канала (старый + новый), не только startup.

Тесты: unit на провайдер (подхват ротации, fallback на ENOENT, пустой файл, loud fail без единого good-токена) + wiring-тест: supervisor получает функцию-провайдер, перезапись файла видна без рестарта, knownTokens доезжает до factory.

Коммит 2: cd1c479 — relative projectRoot в генерируемых конфигах

Что оставалось абсолютным: kimiWork.projectRoot / opencode.projectRoot в ролевых MCP-конфигах. Loader (binding.ts) уже резолвит его от каталога конфига — генератор теперь пишет relative через relativeConfigPath() (forward slashes; absolute fallback при кросс-драйв на Windows — path.relative тогда возвращает absolute). Переезд репозитория/synloqHome больше не ломает конфиги.

Попутный багфикс: inspectChannelConfig проверял projectRoot как absolute-only — с relative-конфигами doctor начал бы флажить здоровые. Теперь резолвит как loader; покрыт и opencode-блок.

Осознанно не тронуто: kimi.plugin.json server args (entrypoint dist/ + configPath) и opencode command array — их резолвит хост, чья семантика относительных путей нам не принадлежит.

Совместимость: старые absolute-конфиги работают как есть (resolve() прозрачен); ближайший doctor --repair перепишет в relative.

Verify

Полный pnpm verify зелёный после rebase на свежий main (723dd27): 108 файлов / 931 тест, format/typecheck/build чистые.

Известные flaky (не из этого PR, падают и на main под параллельной нагрузкой, в изоляции зелёные): credential-concurrency (concurrent issuance) и supervisor-loop election — видел оба по одному разу в verify-прогонах, изолированно и при повторе зелёные.

… (UX 2a)

The MCP stdio bridge read the credential file once at startup; after
rotate-token or doctor --repair a running channel kept 401-looping with
the stale in-memory token until the host process was restarted (the
recovery loop re-registered with the same stale token).

The token now flows through a file-backed TokenProvider: RelayHttpClient
already asks its provider per request, so a rewritten credential file
takes effect on the next call. A transient read failure (Windows sharing
violation, torn rename) falls back to the last successfully read token
instead of breaking a live channel. The supervisor/ensureRelay path
accepts a TokenProvider alongside a static string (backward compatible).

Diagnostics mask every token the channel has ever served (old and new),
not just the startup one.

Tests: provider unit tests (rotation pickup, last-good fallback on
ENOENT, empty file treated as mid-rewrite, loud failure with no good
token) and a wiring test pinning that the supervisor receives a
re-reading provider.
The last absolute path in generated role configs was the bound project
root (kimiWork.projectRoot / opencode.projectRoot). The stdio loader
already resolves it against the config directory, so render it relative
via relativeConfigPath() — forward slashes, absolute fallback when no
relative form exists (cross-drive on Windows). Relocating the project
root or the Synloq home no longer breaks channel configs; doctor
--repair keeps writing byte-identical configs.

inspectChannelConfig now resolves the project root the same way the
loader does (it checked it as absolute-only) and covers the opencode
binding block too — otherwise doctor would have flagged healthy
relative configs.

Deliberately untouched: kimi.plugin.json server args and the opencode
command array — those are resolved by the host, whose relative-path
semantics we do not own.

Backward compatible: existing absolute configs keep working (resolve()
is transparent to them); the next doctor --repair rewrites them in the
relative form.
@OBenner

OBenner commented Nov 16, 2026

Copy link
Copy Markdown
Owner Author

Review (dev) — ACCEPT

Checked against the agreed plan (both decision points approved with the D1 fallback requirement):

2(a) credential self-heal. createTokenFileProvider re-reads the credential file per request and — exactly as required — falls back to the last good token on any read failure (ENOENT, Windows sharing violation, torn rename), so a momentary file problem never drops a live channel; only a truly empty/unreadable credential with no history raises. knownTokens accumulates rotation history and reaches both diagnostic factories (Kimi Work + OpenCode lifecycle), so old and new tokens are masked alike. Supervisor's string | TokenProvider union preserves backward compatibility.

2(b) relative projectRoot. relativeConfigPath renders the target relative to the config directory (forward slashes, absolute fallback when path.relative can't help — cross-drive), and inspectChannelConfig was aligned to the loader's resolution semantics — a genuine companion bugfix: doctor would otherwise flag healthy relative configs. Host-resolved surfaces (kimi.plugin.json args, opencode command array) correctly left untouched, with rationale in the PR body. Old absolute configs keep working; repair rewrites on next run — no migration.

Verified independently in a detached review worktree: 28 targeted tests across credentials/repair/runtime-config/stdio-lifecycle suites, full pnpm verify 108 files / 931 tests PASS.

Non-blocking: cross-drive fallback has no unit test (not reproducible on a single drive) — the logic is the native path.relative contract and is documented; the known load flakes (credential-concurrency, supervisor-loop) remain tracked in #13 and are unrelated.

Passing to CTO for final.

@OBenner
OBenner merged commit d3cd526 into main Nov 16, 2026
3 checks passed
@OBenner
OBenner deleted the feat/ux-repair-relative-paths branch November 16, 2026 17:00
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