Repository navigation
feat: credential re-read self-heal and relative projectRoot in generated configs (UX 2) - #99
Conversation
… (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.
Review (dev) — ACCEPTChecked against the agreed plan (both decision points approved with the D1 fallback requirement): 2(a) credential self-heal. 2(b) relative projectRoot. Verified independently in a detached review worktree: 28 targeted tests across credentials/repair/runtime-config/stdio-lifecycle suites, full Non-blocking: cross-drive fallback has no unit test (not reproducible on a single drive) — the logic is the native Passing to CTO for final. |
Контекст
Вторая половина 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). Перевыпуск действует со следующего запроса, без рестарта.EnsureRelayOptions.token: string | TokenProvider— строка оборачивается (обратная совместимость), probe использует тот же провайдер.Тесты: 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.jsonserver 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-loopelection — видел оба по одному разу в verify-прогонах, изолированно и при повторе зелёные.