From 927a42d54c116a0b354282bc039570dd394e0205 Mon Sep 17 00:00:00 2001 From: seunghan Kim Date: Tue, 13 Oct 2026 20:19:14 +0900 Subject: [PATCH 1/4] =?UTF-8?q?fix(sync):=20=EC=82=AC=EB=9E=8C=EC=9D=B4=20?= =?UTF-8?q?=EC=9D=BD=EB=8A=94=20status=20=EC=B6=9C=EB=A0=A5=C2=B7=EC=84=B1?= =?UTF-8?q?=EA=B3=B5=20=EB=AC=B8=EA=B5=AC=C2=B7polkit=20=EC=97=90=EC=9D=B4?= =?UTF-8?q?=EC=A0=84=ED=8A=B8=20=EB=B6=80=EC=9E=AC=20=EC=95=88=EB=82=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - sync status 텍스트에서 기기 JSON 원문 대신 레이블·이상 표시만 출력(--json 은 그대로) - sync add·resolve·review 성공 시 한 줄 확인, 종료 코드 8이면 남은 일 안내 - pkcheck 종료 2(에이전트 없음)면 원인과 해결 방법을 안내 Refs DCO-40 Co-Authored-By: Claude Opus 5.5 --- crates/kc-cli/locales/de.toml | 24 ++++ crates/kc-cli/locales/es.toml | 24 ++++ crates/kc-cli/locales/fr.toml | 24 ++++ crates/kc-cli/locales/ja.toml | 24 ++++ crates/kc-cli/locales/ko.toml | 24 ++++ crates/kc-cli/locales/zh-Hans.toml | 24 ++++ crates/kc-cli/locales/zh-Hant.toml | 24 ++++ crates/kc-cli/src/commands/sync.rs | 10 ++ crates/kc-cli/src/local_auth.rs | 36 +++++ crates/kc-cli/src/local_auth/linux.rs | 23 +++- crates/kc-cli/src/sync/actions.rs | 189 ++++++++++++++++++++++++-- crates/kc-cli/src/sync/mod.rs | 18 +-- crates/kc-cli/tests/sync.rs | 43 +++++- 13 files changed, 457 insertions(+), 30 deletions(-) diff --git a/crates/kc-cli/locales/de.toml b/crates/kc-cli/locales/de.toml index be4ffdf..48f3f9d 100644 --- a/crates/kc-cli/locales/de.toml +++ b/crates/kc-cli/locales/de.toml @@ -500,3 +500,27 @@ "Ignored a sync offer from disabled or blocked peer {peer}." = "Synchronisierungsangebot vom deaktivierten oder blockierten Gerät {peer} ignoriert." "Sync item held; run `kc sync review`." = "Synchronisierungselement zurückgehalten; `kc sync review` ausführen." "{name} is in conflict; settle it with `kc sync resolve {name}` first." = "{name} steht im Konflikt; zuerst mit `kc sync resolve {name}` auflösen." +"removed from sync" = "aus der Synchronisierung entfernt" +"hasn't answered the sync handshake yet" = "hat auf den Sync-Handshake noch nicht geantwortet" +"paused after too many changes" = "nach zu vielen Änderungen pausiert" +"quarantined: {n}" = "in Quarantäne: {n}" +"re-offer needed: {n}" = "erneuter Vorschlag erforderlich: {n}" +"device {label}: {state}" = "Gerät {label}: {state}" +"Nothing to review." = "Nichts zu prüfen." +"Rejected {name}." = "{name} abgelehnt." +"Accepted {name} from {peer}." = "{name} von {peer} angenommen." +"Left {name} for later." = "{name} für später zurückgestellt." +"Added {name} to sync; there is no paired device to offer it to yet." = "{name} zur Synchronisierung hinzugefügt; es gibt noch kein gekoppeltes Gerät, dem es vorgeschlagen werden kann." +"Added {name} to sync and offered it to {n} device; accept it there with `kc sync review`." = "{name} zur Synchronisierung hinzugefügt und {n} Gerät vorgeschlagen; nehmen Sie es dort mit `kc sync review` an." +"Added {name} to sync and offered it to {n} devices; accept it on each with `kc sync review`." = "{name} zur Synchronisierung hinzugefügt und {n} Geräten vorgeschlagen; nehmen Sie es auf jedem mit `kc sync review` an." +"Resolved {name}, keeping {choice}; the other devices review it with `kc sync review`." = "{name} aufgelöst, der Wert von {choice} bleibt; die anderen Geräte prüfen ihn mit `kc sync review`." +"sync is frozen (`kc sync unfreeze`)" = "Synchronisierung ist eingefroren (`kc sync unfreeze`)" +"sync storage is full" = "Synchronisierungsspeicher ist voll" +"waiting for review on other devices" = "wartet auf Prüfung auf anderen Geräten" +"changes to review here (`kc sync review`)" = "Änderungen zum Prüfen auf diesem Gerät (`kc sync review`)" +"conflicts to resolve (`kc sync resolve`)" = "Konflikte zum Auflösen (`kc sync resolve`)" +"changes queued for delivery (`kc sync`)" = "Änderungen warten auf Zustellung (`kc sync`)" +"a device needs attention (`kc sync status`)" = "ein Gerät braucht Aufmerksamkeit (`kc sync status`)" +"Still pending: {what}." = "Noch offen: {what}." +"No polkit authentication agent is running in this session (for example over SSH, or on a desktop without one such as hyprpolkitagent or polkit-gnome). Run this command from a desktop session that has an agent." = "In dieser Sitzung läuft kein polkit-Authentifizierungsagent (zum Beispiel über SSH oder auf einem Desktop ohne Agent wie hyprpolkitagent oder polkit-gnome). Führen Sie diesen Befehl in einer Desktop-Sitzung mit Agent aus." +"The operating system couldn't ask for confirmation: {reason}." = "Das Betriebssystem konnte keine Bestätigung anfordern: {reason}." diff --git a/crates/kc-cli/locales/es.toml b/crates/kc-cli/locales/es.toml index bf0acc6..2fda5c5 100644 --- a/crates/kc-cli/locales/es.toml +++ b/crates/kc-cli/locales/es.toml @@ -500,3 +500,27 @@ "Ignored a sync offer from disabled or blocked peer {peer}." = "Se ignoró una oferta de sincronización del dispositivo desactivado o bloqueado {peer}." "Sync item held; run `kc sync review`." = "Elemento de sincronización retenido; ejecuta `kc sync review`." "{name} is in conflict; settle it with `kc sync resolve {name}` first." = "{name} está en conflicto; resuélvelo primero con `kc sync resolve {name}`." +"removed from sync" = "quitado de la sincronización" +"hasn't answered the sync handshake yet" = "aún no ha respondido al saludo de sincronización" +"paused after too many changes" = "en pausa tras demasiados cambios" +"quarantined: {n}" = "en cuarentena: {n}" +"re-offer needed: {n}" = "es necesario volver a proponer: {n}" +"device {label}: {state}" = "dispositivo {label}: {state}" +"Nothing to review." = "No hay nada que revisar." +"Rejected {name}." = "Se rechazó {name}." +"Accepted {name} from {peer}." = "Se aceptó {name} de {peer}." +"Left {name} for later." = "{name} queda para más tarde." +"Added {name} to sync; there is no paired device to offer it to yet." = "Se añadió {name} a la sincronización; todavía no hay ningún dispositivo emparejado al que proponerlo." +"Added {name} to sync and offered it to {n} device; accept it there with `kc sync review`." = "Se añadió {name} a la sincronización y se propuso a {n} dispositivo; acéptelo allí con `kc sync review`." +"Added {name} to sync and offered it to {n} devices; accept it on each with `kc sync review`." = "Se añadió {name} a la sincronización y se propuso a {n} dispositivos; acéptelo en cada uno con `kc sync review`." +"Resolved {name}, keeping {choice}; the other devices review it with `kc sync review`." = "Se resolvió {name} conservando el valor de {choice}; los demás dispositivos lo revisan con `kc sync review`." +"sync is frozen (`kc sync unfreeze`)" = "la sincronización está congelada (`kc sync unfreeze`)" +"sync storage is full" = "el almacenamiento de sincronización está lleno" +"waiting for review on other devices" = "pendiente de revisión en otros dispositivos" +"changes to review here (`kc sync review`)" = "cambios por revisar aquí (`kc sync review`)" +"conflicts to resolve (`kc sync resolve`)" = "conflictos por resolver (`kc sync resolve`)" +"changes queued for delivery (`kc sync`)" = "cambios en cola para entregar (`kc sync`)" +"a device needs attention (`kc sync status`)" = "un dispositivo requiere atención (`kc sync status`)" +"Still pending: {what}." = "Aún pendiente: {what}." +"No polkit authentication agent is running in this session (for example over SSH, or on a desktop without one such as hyprpolkitagent or polkit-gnome). Run this command from a desktop session that has an agent." = "No hay ningún agente de autenticación de polkit en ejecución en esta sesión (por ejemplo, por SSH o en un escritorio sin agente como hyprpolkitagent o polkit-gnome). Ejecute este comando desde una sesión de escritorio que tenga un agente." +"The operating system couldn't ask for confirmation: {reason}." = "El sistema operativo no pudo pedir la confirmación: {reason}." diff --git a/crates/kc-cli/locales/fr.toml b/crates/kc-cli/locales/fr.toml index d66f990..f7ba5e9 100644 --- a/crates/kc-cli/locales/fr.toml +++ b/crates/kc-cli/locales/fr.toml @@ -500,3 +500,27 @@ "Ignored a sync offer from disabled or blocked peer {peer}." = "Offre de synchronisation ignorée : appareil {peer} désactivé ou bloqué." "Sync item held; run `kc sync review`." = "Élément de synchronisation en attente ; exécutez `kc sync review`." "{name} is in conflict; settle it with `kc sync resolve {name}` first." = "{name} est en conflit ; résolvez-le d’abord avec `kc sync resolve {name}`." +"removed from sync" = "retiré de la synchronisation" +"hasn't answered the sync handshake yet" = "n’a pas encore répondu à la négociation de synchronisation" +"paused after too many changes" = "en pause après trop de modifications" +"quarantined: {n}" = "en quarantaine : {n}" +"re-offer needed: {n}" = "nouvelle proposition nécessaire : {n}" +"device {label}: {state}" = "appareil {label} : {state}" +"Nothing to review." = "Rien à examiner." +"Rejected {name}." = "{name} refusé." +"Accepted {name} from {peer}." = "{name} accepté depuis {peer}." +"Left {name} for later." = "{name} laissé pour plus tard." +"Added {name} to sync; there is no paired device to offer it to yet." = "{name} ajouté à la synchronisation ; aucun appareil associé à qui le proposer pour l’instant." +"Added {name} to sync and offered it to {n} device; accept it there with `kc sync review`." = "{name} ajouté à la synchronisation et proposé à {n} appareil ; acceptez-le là-bas avec `kc sync review`." +"Added {name} to sync and offered it to {n} devices; accept it on each with `kc sync review`." = "{name} ajouté à la synchronisation et proposé à {n} appareils ; acceptez-le sur chacun avec `kc sync review`." +"Resolved {name}, keeping {choice}; the other devices review it with `kc sync review`." = "{name} résolu en gardant la valeur de {choice} ; les autres appareils l’examinent avec `kc sync review`." +"sync is frozen (`kc sync unfreeze`)" = "la synchronisation est gelée (`kc sync unfreeze`)" +"sync storage is full" = "le stockage de synchronisation est plein" +"waiting for review on other devices" = "en attente de vérification sur d’autres appareils" +"changes to review here (`kc sync review`)" = "modifications à examiner ici (`kc sync review`)" +"conflicts to resolve (`kc sync resolve`)" = "conflits à résoudre (`kc sync resolve`)" +"changes queued for delivery (`kc sync`)" = "modifications en attente d’envoi (`kc sync`)" +"a device needs attention (`kc sync status`)" = "un appareil demande votre attention (`kc sync status`)" +"Still pending: {what}." = "Encore en attente : {what}." +"No polkit authentication agent is running in this session (for example over SSH, or on a desktop without one such as hyprpolkitagent or polkit-gnome). Run this command from a desktop session that has an agent." = "Aucun agent d’authentification polkit ne tourne dans cette session (par exemple via SSH, ou sur un bureau sans agent tel que hyprpolkitagent ou polkit-gnome). Exécutez cette commande depuis une session de bureau qui en a un." +"The operating system couldn't ask for confirmation: {reason}." = "Le système d’exploitation n’a pas pu demander la confirmation : {reason}." diff --git a/crates/kc-cli/locales/ja.toml b/crates/kc-cli/locales/ja.toml index 0878dd7..3bc49b3 100644 --- a/crates/kc-cli/locales/ja.toml +++ b/crates/kc-cli/locales/ja.toml @@ -500,3 +500,27 @@ "Ignored a sync offer from disabled or blocked peer {peer}." = "無効またはブロックされたデバイス{peer}からの同期提案を無視しました。" "Sync item held; run `kc sync review`." = "同期項目を保留しました。`kc sync review`を実行してください。" "{name} is in conflict; settle it with `kc sync resolve {name}` first." = "{name} は競合中です。先に `kc sync resolve {name}` で解決してください。" +"removed from sync" = "同期から外した" +"hasn't answered the sync handshake yet" = "同期ハンドシェイクの応答待ち" +"paused after too many changes" = "変更が多すぎるため一時停止中" +"quarantined: {n}" = "隔離: {n}" +"re-offer needed: {n}" = "再提案が必要: {n}" +"device {label}: {state}" = "デバイス {label}: {state}" +"Nothing to review." = "確認する項目はありません。" +"Rejected {name}." = "{name} を拒否しました。" +"Accepted {name} from {peer}." = "{peer} からの {name} を受け入れました。" +"Left {name} for later." = "{name} は後で確認します。" +"Added {name} to sync; there is no paired device to offer it to yet." = "{name} を同期に追加しました。提案先のペアリング済みデバイスはまだありません。" +"Added {name} to sync and offered it to {n} device; accept it there with `kc sync review`." = "{name} を同期に追加し、{n} 台のデバイスに提案しました。そのデバイスで `kc sync review` を実行して受け入れてください。" +"Added {name} to sync and offered it to {n} devices; accept it on each with `kc sync review`." = "{name} を同期に追加し、{n} 台のデバイスに提案しました。各デバイスで `kc sync review` を実行して受け入れてください。" +"Resolved {name}, keeping {choice}; the other devices review it with `kc sync review`." = "{name} を {choice} の値で解決しました。他のデバイスでは `kc sync review` で確認します。" +"sync is frozen (`kc sync unfreeze`)" = "同期が停止中(`kc sync unfreeze`)" +"sync storage is full" = "同期の保存領域がいっぱい" +"waiting for review on other devices" = "他のデバイスでの確認待ち" +"changes to review here (`kc sync review`)" = "このデバイスで確認する変更あり(`kc sync review`)" +"conflicts to resolve (`kc sync resolve`)" = "解決が必要な競合あり(`kc sync resolve`)" +"changes queued for delivery (`kc sync`)" = "送信待ちの変更あり(`kc sync`)" +"a device needs attention (`kc sync status`)" = "対応が必要なデバイスあり(`kc sync status`)" +"Still pending: {what}." = "未完了: {what}。" +"No polkit authentication agent is running in this session (for example over SSH, or on a desktop without one such as hyprpolkitagent or polkit-gnome). Run this command from a desktop session that has an agent." = "このセッションでは polkit 認証エージェントが動作していません(SSH 接続や、hyprpolkitagent・polkit-gnome などのエージェントがないデスクトップなど)。認証エージェントのあるデスクトップセッションでこのコマンドを実行してください。" +"The operating system couldn't ask for confirmation: {reason}." = "OS が確認を求められませんでした: {reason}。" diff --git a/crates/kc-cli/locales/ko.toml b/crates/kc-cli/locales/ko.toml index f6c24cc..b6397dd 100644 --- a/crates/kc-cli/locales/ko.toml +++ b/crates/kc-cli/locales/ko.toml @@ -500,3 +500,27 @@ "Ignored a sync offer from disabled or blocked peer {peer}." = "비활성화되거나 차단된 기기 {peer}의 동기화 제안을 무시했습니다." "Sync item held; run `kc sync review`." = "동기화 항목을 보류했습니다. `kc sync review`를 실행하세요." "{name} is in conflict; settle it with `kc sync resolve {name}` first." = "{name} 항목이 충돌 중입니다. 먼저 `kc sync resolve {name}`로 해결하세요." +"removed from sync" = "동기화에서 뺌" +"hasn't answered the sync handshake yet" = "아직 동기화 연결 응답 없음" +"paused after too many changes" = "변경이 너무 많아 일시 중지됨" +"quarantined: {n}" = "격리: {n}개" +"re-offer needed: {n}" = "다시 제안 필요: {n}개" +"device {label}: {state}" = "기기 {label}: {state}" +"Nothing to review." = "검토할 항목이 없습니다." +"Rejected {name}." = "{name}을(를) 거절했습니다." +"Accepted {name} from {peer}." = "{peer}에서 온 {name}을(를) 받아들였습니다." +"Left {name} for later." = "{name}은(는) 나중에 결정합니다." +"Added {name} to sync; there is no paired device to offer it to yet." = "{name}을(를) 동기화에 추가했습니다. 아직 제안할 페어링 기기가 없습니다." +"Added {name} to sync and offered it to {n} device; accept it there with `kc sync review`." = "{name}을(를) 동기화에 추가하고 기기 {n}대에 제안했습니다. 그 기기에서 `kc sync review`로 받아들이세요." +"Added {name} to sync and offered it to {n} devices; accept it on each with `kc sync review`." = "{name}을(를) 동기화에 추가하고 기기 {n}대에 제안했습니다. 각 기기에서 `kc sync review`로 받아들이세요." +"Resolved {name}, keeping {choice}; the other devices review it with `kc sync review`." = "{name}을(를) {choice}의 값으로 해결했습니다. 다른 기기에서 `kc sync review`로 검토합니다." +"sync is frozen (`kc sync unfreeze`)" = "동기화가 중지됨(`kc sync unfreeze`)" +"sync storage is full" = "동기화 저장 공간이 가득 참" +"waiting for review on other devices" = "다른 기기의 검토를 기다리는 중" +"changes to review here (`kc sync review`)" = "이 기기에서 검토할 변경 있음(`kc sync review`)" +"conflicts to resolve (`kc sync resolve`)" = "해결할 충돌 있음(`kc sync resolve`)" +"changes queued for delivery (`kc sync`)" = "전송 대기 중인 변경 있음(`kc sync`)" +"a device needs attention (`kc sync status`)" = "확인이 필요한 기기 있음(`kc sync status`)" +"Still pending: {what}." = "아직 남은 일: {what}." +"No polkit authentication agent is running in this session (for example over SSH, or on a desktop without one such as hyprpolkitagent or polkit-gnome). Run this command from a desktop session that has an agent." = "이 세션에는 polkit 인증 에이전트가 실행 중이지 않습니다(예: SSH 접속, 또는 hyprpolkitagent·polkit-gnome 같은 에이전트가 없는 데스크톱). 인증 에이전트가 있는 데스크톱 세션에서 이 명령을 실행하세요." +"The operating system couldn't ask for confirmation: {reason}." = "운영체제가 본인 확인을 요청하지 못했습니다: {reason}." diff --git a/crates/kc-cli/locales/zh-Hans.toml b/crates/kc-cli/locales/zh-Hans.toml index 1ed5632..7bfb09c 100644 --- a/crates/kc-cli/locales/zh-Hans.toml +++ b/crates/kc-cli/locales/zh-Hans.toml @@ -500,3 +500,27 @@ "Ignored a sync offer from disabled or blocked peer {peer}." = "已忽略已禁用或被阻止的设备{peer}的同步提议。" "Sync item held; run `kc sync review`." = "同步项目已保留;请运行 `kc sync review`。" "{name} is in conflict; settle it with `kc sync resolve {name}` first." = "{name} 存在冲突,请先用 `kc sync resolve {name}` 解决。" +"removed from sync" = "已移出同步" +"hasn't answered the sync handshake yet" = "尚未回应同步握手" +"paused after too many changes" = "因更改过多已暂停" +"quarantined: {n}" = "已隔离:{n}" +"re-offer needed: {n}" = "需要重新提议:{n}" +"device {label}: {state}" = "设备 {label}:{state}" +"Nothing to review." = "没有需要审核的项目。" +"Rejected {name}." = "已拒绝 {name}。" +"Accepted {name} from {peer}." = "已接受来自 {peer} 的 {name}。" +"Left {name} for later." = "{name} 留待稍后处理。" +"Added {name} to sync; there is no paired device to offer it to yet." = "已将 {name} 加入同步;目前还没有可提议的已配对设备。" +"Added {name} to sync and offered it to {n} device; accept it there with `kc sync review`." = "已将 {name} 加入同步并提议给 {n} 台设备;请在该设备上用 `kc sync review` 接受。" +"Added {name} to sync and offered it to {n} devices; accept it on each with `kc sync review`." = "已将 {name} 加入同步并提议给 {n} 台设备;请在每台设备上用 `kc sync review` 接受。" +"Resolved {name}, keeping {choice}; the other devices review it with `kc sync review`." = "已解决 {name},保留 {choice} 的值;其他设备用 `kc sync review` 审核。" +"sync is frozen (`kc sync unfreeze`)" = "同步已冻结(`kc sync unfreeze`)" +"sync storage is full" = "同步存储空间已满" +"waiting for review on other devices" = "等待其他设备审核" +"changes to review here (`kc sync review`)" = "此设备有待审核的更改(`kc sync review`)" +"conflicts to resolve (`kc sync resolve`)" = "有待解决的冲突(`kc sync resolve`)" +"changes queued for delivery (`kc sync`)" = "有等待发送的更改(`kc sync`)" +"a device needs attention (`kc sync status`)" = "有设备需要处理(`kc sync status`)" +"Still pending: {what}." = "仍待处理:{what}。" +"No polkit authentication agent is running in this session (for example over SSH, or on a desktop without one such as hyprpolkitagent or polkit-gnome). Run this command from a desktop session that has an agent." = "此会话中没有运行 polkit 身份验证代理(例如通过 SSH 连接,或桌面上没有 hyprpolkitagent、polkit-gnome 之类的代理)。请在有身份验证代理的桌面会话中运行此命令。" +"The operating system couldn't ask for confirmation: {reason}." = "操作系统无法请求确认:{reason}。" diff --git a/crates/kc-cli/locales/zh-Hant.toml b/crates/kc-cli/locales/zh-Hant.toml index e93c253..3d564d1 100644 --- a/crates/kc-cli/locales/zh-Hant.toml +++ b/crates/kc-cli/locales/zh-Hant.toml @@ -500,3 +500,27 @@ "Ignored a sync offer from disabled or blocked peer {peer}." = "已忽略已停用或遭封鎖的裝置{peer}的同步提議。" "Sync item held; run `kc sync review`." = "同步項目已保留;請執行 `kc sync review`。" "{name} is in conflict; settle it with `kc sync resolve {name}` first." = "{name} 有衝突,請先用 `kc sync resolve {name}` 解決。" +"removed from sync" = "已移出同步" +"hasn't answered the sync handshake yet" = "尚未回應同步交握" +"paused after too many changes" = "因變更過多已暫停" +"quarantined: {n}" = "已隔離:{n}" +"re-offer needed: {n}" = "需要重新提議:{n}" +"device {label}: {state}" = "裝置 {label}:{state}" +"Nothing to review." = "沒有需要審核的項目。" +"Rejected {name}." = "已拒絕 {name}。" +"Accepted {name} from {peer}." = "已接受來自 {peer} 的 {name}。" +"Left {name} for later." = "{name} 留待稍後處理。" +"Added {name} to sync; there is no paired device to offer it to yet." = "已將 {name} 加入同步;目前還沒有可提議的已配對裝置。" +"Added {name} to sync and offered it to {n} device; accept it there with `kc sync review`." = "已將 {name} 加入同步並提議給 {n} 台裝置;請在該裝置上用 `kc sync review` 接受。" +"Added {name} to sync and offered it to {n} devices; accept it on each with `kc sync review`." = "已將 {name} 加入同步並提議給 {n} 台裝置;請在每台裝置上用 `kc sync review` 接受。" +"Resolved {name}, keeping {choice}; the other devices review it with `kc sync review`." = "已解決 {name},保留 {choice} 的值;其他裝置用 `kc sync review` 審核。" +"sync is frozen (`kc sync unfreeze`)" = "同步已凍結(`kc sync unfreeze`)" +"sync storage is full" = "同步儲存空間已滿" +"waiting for review on other devices" = "等待其他裝置審核" +"changes to review here (`kc sync review`)" = "此裝置有待審核的變更(`kc sync review`)" +"conflicts to resolve (`kc sync resolve`)" = "有待解決的衝突(`kc sync resolve`)" +"changes queued for delivery (`kc sync`)" = "有等待傳送的變更(`kc sync`)" +"a device needs attention (`kc sync status`)" = "有裝置需要處理(`kc sync status`)" +"Still pending: {what}." = "仍待處理:{what}。" +"No polkit authentication agent is running in this session (for example over SSH, or on a desktop without one such as hyprpolkitagent or polkit-gnome). Run this command from a desktop session that has an agent." = "此工作階段中沒有執行 polkit 驗證代理程式(例如透過 SSH 連線,或桌面上沒有 hyprpolkitagent、polkit-gnome 之類的代理程式)。請在有驗證代理程式的桌面工作階段中執行此命令。" +"The operating system couldn't ask for confirmation: {reason}." = "作業系統無法要求確認:{reason}。" diff --git a/crates/kc-cli/src/commands/sync.rs b/crates/kc-cli/src/commands/sync.rs index 15545a5..2144e88 100644 --- a/crates/kc-cli/src/commands/sync.rs +++ b/crates/kc-cli/src/commands/sync.rs @@ -20,6 +20,16 @@ pub(super) async fn run(ctx: &mut Ctx<'_, H>, args: SyncArgs) -> Result let code = sync::actions::command(ctx, command)?; if !quiet { sync::flush(ctx, false).await?; + if code == 8 { + let notes = sync::actions::pending_notes(&State::load(&ctx.state)?); + if !notes.is_empty() { + say!( + ctx, + "{}", + tr!("Still pending: {what}.", what = notes.join("; ")) + ); + } + } } return Ok(code); } diff --git a/crates/kc-cli/src/local_auth.rs b/crates/kc-cli/src/local_auth.rs index 0d54a73..129ce04 100644 --- a/crates/kc-cli/src/local_auth.rs +++ b/crates/kc-cli/src/local_auth.rs @@ -11,6 +11,8 @@ mod windows; #[cfg(any(target_os = "linux", test))] mod linux; +use crate::i18n::tr; + /// The result of an OS user-presence check. #[derive(Debug, Clone, PartialEq)] pub enum LocalAuthOutcome { @@ -19,6 +21,26 @@ pub enum LocalAuthOutcome { Unavailable(String), } +/// The start of the [`LocalAuthOutcome::Unavailable`] reason when polkit has no +/// authentication agent to ask (pkcheck exit 2). +pub(crate) const NO_POLKIT_AGENT: &str = "no polkit authentication agent"; + +impl LocalAuthOutcome { + /// What to do about a refused confirmation, for the error's hint. + pub(crate) fn hint(&self) -> String { + match self { + LocalAuthOutcome::Unavailable(reason) if reason.starts_with(NO_POLKIT_AGENT) => tr!( + "No polkit authentication agent is running in this session (for example over SSH, or on a desktop without one such as hyprpolkitagent or polkit-gnome). Run this command from a desktop session that has an agent." + ), + LocalAuthOutcome::Unavailable(reason) => tr!( + "The operating system couldn't ask for confirmation: {reason}.", + reason = reason + ), + _ => tr!("Run this command at a terminal and confirm in the operating system."), + } + } +} + /// Blocks for a fresh OS confirmation, showing `reason` in the authentication UI. pub fn confirm(reason: &str) -> LocalAuthOutcome { // LocalAuthentication throws an Objective-C exception for an empty reason. @@ -52,6 +74,20 @@ mod tests { assert!(matches!(confirm(" \t\n"), LocalAuthOutcome::Unavailable(_))); } + #[test] + fn hint_names_a_missing_polkit_agent_and_shows_other_reasons() { + let no_agent = LocalAuthOutcome::Unavailable(format!( + "{NO_POLKIT_AGENT}: Authorization requires authentication but no agent is available." + )); + assert!(no_agent.hint().contains("polkit authentication agent")); + let other = LocalAuthOutcome::Unavailable("cannot run pkcheck: not found".into()); + assert!(other.hint().contains("cannot run pkcheck: not found")); + assert_eq!( + LocalAuthOutcome::Denied.hint(), + "Run this command at a terminal and confirm in the operating system." + ); + } + #[test] #[ignore = "requires a human to answer the OS authentication prompt"] fn manual_local_confirmation() { diff --git a/crates/kc-cli/src/local_auth/linux.rs b/crates/kc-cli/src/local_auth/linux.rs index 8891251..c9ce8fe 100644 --- a/crates/kc-cli/src/local_auth/linux.rs +++ b/crates/kc-cli/src/local_auth/linux.rs @@ -57,8 +57,13 @@ fn outcome(code: Option, stderr: &[u8]) -> LocalAuthOutcome { match code { Some(0) => LocalAuthOutcome::Confirmed, // pkcheck(1): 1 = not authorized, 3 = dialog dismissed. 2 means user interaction was - // needed but no authentication agent could ask, which falls to Unavailable below. + // needed but no authentication agent could ask: Unavailable, named so the hint can say so. Some(1 | 3) => LocalAuthOutcome::Denied, + Some(2) => LocalAuthOutcome::Unavailable(format!( + "{}: {}", + super::NO_POLKIT_AGENT, + String::from_utf8_lossy(stderr).trim() + )), _ => LocalAuthOutcome::Unavailable(format!( "pkcheck failed (exit {code:?}): {}", String::from_utf8_lossy(stderr).trim() @@ -141,4 +146,20 @@ mod tests { } } } + + #[test] + fn exit_2_is_a_missing_agent() { + let stderr = b"Authorization requires authentication but no agent is available.\n"; + match outcome(Some(2), stderr) { + LocalAuthOutcome::Unavailable(message) => { + assert!(message.starts_with(super::super::NO_POLKIT_AGENT)); + assert!(message.ends_with("no agent is available.")); + } + result => panic!("unexpected outcome: {result:?}"), + } + assert!(!matches!( + outcome(Some(127), stderr), + LocalAuthOutcome::Unavailable(m) if m.starts_with(super::super::NO_POLKIT_AGENT) + )); + } } diff --git a/crates/kc-cli/src/sync/actions.rs b/crates/kc-cli/src/sync/actions.rs index 89409ae..47a3dc6 100644 --- a/crates/kc-cli/src/sync/actions.rs +++ b/crates/kc-cli/src/sync/actions.rs @@ -126,6 +126,90 @@ pub(crate) fn remove(ctx: &Ctx<'_, H>, s: &mut State, name: &str) -> Re super::transport::collect_snapshots(s); s.cleanup(ctx) } +/// One `kc sync status` row for people: an item (`peers`) or a candidate (`peer`). +fn row_line(row: &serde_json::Value) -> String { + let peers = match (&row["peer"], &row["peers"]) { + (serde_json::Value::String(peer), _) => peer.clone(), + (_, serde_json::Value::Array(peers)) if !peers.is_empty() => peers + .iter() + .filter_map(|p| p.as_str()) + .collect::>() + .join(", "), + _ => "-".into(), + }; + format!( + "{} {} {} {}", + row["name"].as_str().unwrap_or(""), + row["state"].as_str().unwrap_or(""), + row["fingerprint"].as_str().unwrap_or("-"), + peers + ) +} +/// One device line for people, naming only what needs attention. +fn peer_line(peer: &serde_json::Value) -> String { + let count = |key: &str| peer[key].as_array().map_or(0, Vec::len); + let mut flags = Vec::new(); + if peer["enabled"] == false { + flags.push(tr!("removed from sync")); + } + if peer["v2"] == false { + flags.push(tr!("hasn't answered the sync handshake yet")); + } + if peer["breaker"] == true { + flags.push(tr!("paused after too many changes")); + } + if count("quarantine") > 0 { + flags.push(tr!("quarantined: {n}", n = count("quarantine"))); + } + if count("reoffer") > 0 { + flags.push(tr!("re-offer needed: {n}", n = count("reoffer"))); + } + let state = if flags.is_empty() { + tr!("ok") + } else { + flags.join(", ") + }; + tr!( + "device {label}: {state}", + label = peer["label"].as_str().unwrap_or(""), + state = state + ) +} +/// What keeps sync at exit code 8, for people. Mirrors [`pending`]. +pub(crate) fn pending_notes(s: &State) -> Vec { + let mut notes = Vec::new(); + if s.frozen { + notes.push(tr!("sync is frozen (`kc sync unfreeze`)")); + } + if s.capacity_blocked { + notes.push(tr!("sync storage is full")); + } + if !s.offers.is_empty() { + notes.push(tr!("waiting for review on other devices")); + } + if !s.candidates.is_empty() { + notes.push(tr!("changes to review here (`kc sync review`)")); + } + if s.items.values().any(|i| i.conflict) { + notes.push(tr!("conflicts to resolve (`kc sync resolve`)")); + } + if s.reconnect + || s.delivery_failed + || s.peers + .keys() + .any(|p| s.outbox.pending(&PeerId(p.clone())).next().is_some()) + { + notes.push(tr!("changes queued for delivery (`kc sync`)")); + } + if s.peers.iter().any(|(p, peer)| { + !peer.reoffer.is_empty() + || !peer.quarantine.is_empty() + || s.limiter.is_tripped(&PeerId(p.clone())) + }) { + notes.push(tr!("a device needs attention (`kc sync status`)")); + } + notes +} pub(crate) fn status(ctx: &mut Ctx<'_, H>, json: bool) -> Result { let _items = ctx.state.lock_items(ctx.store.namespace())?; let _state = ctx.state.lock()?; @@ -206,21 +290,10 @@ pub(crate) fn status(ctx: &mut Ctx<'_, H>, json: bool) -> Result { )?; } else { for row in rows.iter().chain(&candidates) { - ctx.emit( - format!( - "{} {} {} {}\n", - row["name"].as_str().unwrap_or(""), - row["state"].as_str().unwrap_or(""), - row["fingerprint"].as_str().unwrap_or("-"), - row.get("peer") - .cloned() - .unwrap_or_else(|| row["peers"].clone()) - ) - .as_bytes(), - )?; + ctx.emit(format!("{}\n", row_line(row)).as_bytes())?; } - for peer in peers { - ctx.emit(format!("{}\n", peer).as_bytes())?; + for peer in &peers { + ctx.emit(format!("{}\n", peer_line(peer)).as_bytes())?; } if s.capacity_blocked { crate::commands::say!( @@ -263,8 +336,12 @@ pub(crate) fn review(ctx: &mut Ctx<'_, H>) -> Result { .cloned() .collect::>() }; + if candidates.is_empty() { + crate::commands::say!(ctx, "{}", tr!("Nothing to review.")); + } let mut accepts = Vec::new(); let mut rejects = Vec::new(); + let mut later = Vec::new(); for c in candidates { let fingerprint = if c.retire { "-".into() @@ -291,7 +368,7 @@ pub(crate) fn review(ctx: &mut Ctx<'_, H>) -> Result { )? { 0 => accepts.push(c), 1 => rejects.push(c), - _ => {} + _ => later.push(c.version.name), } } if !accepts.is_empty() || !rejects.is_empty() { @@ -334,8 +411,10 @@ pub(crate) fn review(ctx: &mut Ctx<'_, H>) -> Result { let _state = ctx.state.lock()?; let mut s = State::load(&ctx.state)?; scan(ctx, &mut s)?; + let mut done = Vec::new(); for c in rejects { if let Some(current) = s.candidates.remove(&c.version.slot) { + done.push(tr!("Rejected {name}.", name = c.version.name)); release(&mut s, ¤t.version.slot); s.gc.insert(current.base_record); let delivery = delivery_key(&c.peer, &c.version.name, c.generation, c.version.vid); @@ -375,9 +454,20 @@ pub(crate) fn review(ctx: &mut Ctx<'_, H>) -> Result { && current.category != CandidateKind::Conflict { transaction::accept(ctx, &mut s, ¤t)?; + done.push(tr!( + "Accepted {name} from {peer}.", + name = c.version.name, + peer = label(ctx, &c.peer)? + )); } } s.cleanup(ctx)?; + for line in done { + crate::commands::say!(ctx, "{line}"); + } + for name in later { + crate::commands::say!(ctx, "{}", tr!("Left {name} for later.", name = name)); + } Ok(if pending(&s) { 8 } else { 0 }) } pub(crate) fn command(ctx: &mut Ctx<'_, H>, mut command: SyncCommand) -> Result { @@ -442,9 +532,11 @@ pub(crate) fn command(ctx: &mut Ctx<'_, H>, mut command: SyncCommand) - let _state = ctx.state.lock()?; let mut s = State::load(&ctx.state)?; recover(ctx, &mut s)?; + let mut done = Vec::new(); match command { SyncCommand::Add { names, peers } => { let peers = selected_peers(ctx, &s, &peers)?; + let mut added = Vec::new(); for name in &names { crate::values::item_name(name)?; let (v, _, _) = current(ctx, name)?.ok_or_else(state_error)?; @@ -472,6 +564,28 @@ pub(crate) fn command(ctx: &mut Ctx<'_, H>, mut command: SyncCommand) - } let _ = (value, kind); offer(ctx, &mut s, &name, &peers)?; + added.push(name); + } + for name in added { + done.push(match peers.len() { + 0 => tr!( + "Added {name} to sync; there is no paired device to offer it to yet.", + name = name + ), + n => crate::commands::plural_tr( + n, + tr!( + "Added {name} to sync and offered it to {n} device; accept it there with `kc sync review`.", + name = name, + n = n + ), + tr!( + "Added {name} to sync and offered it to {n} devices; accept it on each with `kc sync review`.", + name = name, + n = n + ), + ), + }); } } SyncCommand::Offer { names, peers } => { @@ -535,6 +649,11 @@ pub(crate) fn command(ctx: &mut Ctx<'_, H>, mut command: SyncCommand) - } SyncCommand::Resolve { name, keep } => { scan(ctx, &mut s)?; + let choice = if keep == "mine" { + tr!("this device") + } else { + keep.clone() + }; let was_proposal = !s.items.contains_key(&name); if was_proposal { let scope = s @@ -601,6 +720,11 @@ pub(crate) fn command(ctx: &mut Ctx<'_, H>, mut command: SyncCommand) - (Zeroizing::new(value.value.expose().to_vec()), value.kind) }; transaction::resolve_value(ctx, &mut s, &name, &value, kind)?; + done.push(tr!( + "Resolved {name}, keeping {choice}; the other devices review it with `kc sync review`.", + name = name, + choice = choice + )); } SyncCommand::Peer { command } => match command { SyncPeerCommand::List => { @@ -667,5 +791,40 @@ pub(crate) fn command(ctx: &mut Ctx<'_, H>, mut command: SyncCommand) - _ => {} } s.cleanup(ctx)?; + for line in done { + crate::commands::say!(ctx, "{line}"); + } Ok(if pending(&s) { 8 } else { 0 }) } + +#[cfg(test)] +mod tests { + use super::{peer_line, row_line}; + use serde_json::json; + + #[test] + fn status_rows_list_peers_without_json_syntax() { + let item = json!({"name": "KEY", "state": "in sync", "fingerprint": "ab12", + "peers": ["omarchy", "host.local"]}); + assert_eq!(row_line(&item), "KEY in sync ab12 omarchy, host.local"); + let lonely = json!({"name": "KEY", "state": "in sync", "fingerprint": null, "peers": []}); + assert_eq!(row_line(&lonely), "KEY in sync - -"); + let candidate = json!({"name": "KEY", "state": "proposal", "peer": "omarchy", + "vid": [0], "fingerprint": "cd34"}); + assert_eq!(row_line(&candidate), "KEY proposal cd34 omarchy"); + } + + #[test] + fn status_peer_lines_name_only_what_needs_attention() { + let healthy = json!({"label": "omarchy", "enabled": true, "v2": true, "breaker": false, + "quarantine": [], "last_digest": 1, "reoffer": []}); + assert_eq!(peer_line(&healthy), "device omarchy: ok"); + let troubled = json!({"label": "host.local", "enabled": false, "v2": false, + "breaker": true, "quarantine": ["A", "B"], "last_digest": null, "reoffer": ["A"]}); + assert_eq!( + peer_line(&troubled), + "device host.local: removed from sync, hasn't answered the sync handshake yet, \ + paused after too many changes, quarantined: 2, re-offer needed: 1" + ); + } +} diff --git a/crates/kc-cli/src/sync/mod.rs b/crates/kc-cli/src/sync/mod.rs index d54b406..0092a52 100644 --- a/crates/kc-cli/src/sync/mod.rs +++ b/crates/kc-cli/src/sync/mod.rs @@ -32,14 +32,16 @@ pub(crate) fn state_error() -> CliError { )) } pub(crate) fn human(ctx: &mut Ctx<'_, H>, reason: &str) -> Result<()> { - if !ctx.interactive() || ctx.host.local_confirm(reason) != LocalAuthOutcome::Confirmed { - return Err( - CliError::interaction(tr!("Sync needs local confirmation.")).with_hint(tr!( - "Run this command at a terminal and confirm in the operating system." - )), - ); - } - Ok(()) + let hint = if !ctx.interactive() { + tr!("Run this command at a terminal and confirm in the operating system.") + } else { + match ctx.host.local_confirm(reason) { + LocalAuthOutcome::Confirmed => return Ok(()), + // Unavailable carries why (e.g. no polkit agent); say so instead of the generic hint. + outcome => outcome.hint(), + } + }; + Err(CliError::interaction(tr!("Sync needs local confirmation.")).with_hint(hint)) } pub(crate) fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() diff --git a/crates/kc-cli/tests/sync.rs b/crates/kc-cli/tests/sync.rs index b3da08e..6b73641 100644 --- a/crates/kc-cli/tests/sync.rs +++ b/crates/kc-cli/tests/sync.rs @@ -55,9 +55,22 @@ async fn pump(a: &Device, b: &Device) { } async fn enroll(a: &Device, b: &Device) { a.set("KEY", b"fake-initial-secret").await; - a.run(&["sync", "add", "KEY", "--peers", "bravo"], human(vec![])) - .await - .expect(8); + let out = a + .run(&["sync", "add", "KEY", "--peers", "bravo"], human(vec![])) + .await; + out.expect(8); + assert!( + out.stderr + .contains("Added KEY to sync and offered it to 1 device;"), + "{}", + out.stderr + ); + assert!( + out.stderr + .contains("Still pending: waiting for review on other devices"), + "{}", + out.stderr + ); pump(a, b).await; assert!(b.value("KEY").is_none()); assert_eq!(state(b)["candidates"].as_object().unwrap().len(), 1); @@ -65,6 +78,11 @@ async fn enroll(a: &Device, b: &Device) { .run(&["sync", "review"], human(vec![Answer::Select(0)])) .await; assert!([0, 8].contains(&out.code), "{}", out.stderr); + assert!( + out.stderr.contains("Accepted KEY from alpha."), + "{}", + out.stderr + ); assert_eq!( out.prompts .iter() @@ -101,6 +119,13 @@ async fn add_offer_review_local_confirmation_and_accept_on_both_sides() { let (a, b, _) = devices().await; enroll(&a, &b).await; assert_eq!(a.value("KEY"), b.value("KEY")); + let out = a.run(&["sync", "status"], Run::agent()).await; + out.expect(0); + let text = out.stdout_text(); + assert!(text.contains("KEY in sync "), "{text}"); + assert!(text.contains(" bravo\n"), "{text}"); + assert!(text.contains("device bravo: ok\n"), "{text}"); + assert!(!text.contains('{') && !text.contains('['), "{text}"); a.run(&["sync", "status", "--json"], Run::agent()) .await .expect(0); @@ -156,9 +181,15 @@ async fn concurrent_changes_conflict_resolve_is_held_then_converges() { pump(&a, &b).await; assert_eq!(state(&a)["items"]["KEY"]["conflict"], true); assert_eq!(state(&b)["items"]["KEY"]["conflict"], true); - a.run(&["sync", "resolve", "KEY", "--keep", "mine"], human(vec![])) - .await - .expect(8); + let out = a + .run(&["sync", "resolve", "KEY", "--keep", "mine"], human(vec![])) + .await; + out.expect(8); + assert!( + out.stderr.contains("Resolved KEY, keeping this device;"), + "{}", + out.stderr + ); pump(&a, &b).await; assert_eq!(b.value("KEY").unwrap(), b"fake-bravo-change"); b.run(&["sync", "review"], human(vec![Answer::Select(0)])) From b08b4fee628e526724bde8cc2b0e295b982d3dce Mon Sep 17 00:00:00 2001 From: seunghan Kim Date: Tue, 13 Oct 2026 20:31:56 +0900 Subject: [PATCH 2/4] =?UTF-8?q?fix(sync):=20=EC=B6=95=EC=B6=9C=20=EB=B0=94?= =?UTF-8?q?=EC=9D=B8=EB=94=A9=20=EB=88=84=EC=88=98=C2=B7=EA=B1=B0=EC=A0=88?= =?UTF-8?q?=20=EA=B8=B0=EB=A1=9D=20=EB=A7=8C=EB=A3=8C=C2=B7legacy=20?= =?UTF-8?q?=EC=88=98=EB=9D=BD=20=EC=A0=84=ED=8C=8C=C2=B7=EB=8C=80=EC=B2=B4?= =?UTF-8?q?=EB=90=9C=20=EB=B3=B4=EB=A5=98=EB=B6=84=20=EC=A0=95=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 수락 중인 후보를 축출에서 보호(pin)하고, 축출된 후보의 vid 바인딩을 정리 - 거절한 제안 기록에 30일 슬라이딩 만료(rejected_until, 구 상태 파일과 호환) - 걸린 후보가 없는 unbound 바인딩을 참조 기준으로 정리 - legacy 로 받아들인 값을 이 기기 변경으로 기록해 범위 기기에 전송 - 같은 기기의 나중 변경이 이어받은 보류분은 퇴역시키고 review 에서 제외 Refs DCO-40 Co-Authored-By: Claude Opus 5.5 --- crates/kc-cli/src/sync/actions.rs | 3 +- crates/kc-cli/src/sync/mod.rs | 88 +++++- crates/kc-cli/src/sync/receive.rs | 17 +- crates/kc-cli/src/sync/state.rs | 4 + crates/kc-cli/src/sync/transaction.rs | 187 ++++++++++++- crates/kc-cli/tests/sync.rs | 380 +++++++++++++++++++++++++- crates/kc-sync/src/slots.rs | 5 + docs/design/sync.md | 2 +- 8 files changed, 661 insertions(+), 25 deletions(-) diff --git a/crates/kc-cli/src/sync/actions.rs b/crates/kc-cli/src/sync/actions.rs index 47a3dc6..7a55e3d 100644 --- a/crates/kc-cli/src/sync/actions.rs +++ b/crates/kc-cli/src/sync/actions.rs @@ -333,6 +333,7 @@ pub(crate) fn review(ctx: &mut Ctx<'_, H>) -> Result { s.candidates .values() .filter(|c| c.category != CandidateKind::Conflict) + .filter(|c| !transaction::is_superseded(&s, c)) .cloned() .collect::>() }; @@ -419,7 +420,7 @@ pub(crate) fn review(ctx: &mut Ctx<'_, H>) -> Result { s.gc.insert(current.base_record); let delivery = delivery_key(&c.peer, &c.version.name, c.generation, c.version.vid); if c.category == CandidateKind::Proposal { - s.rejected_offers.insert(delivery); + reject_offer(&mut s, delivery, ctx.host.now()); forget_binding(&mut s, &c.version.name, c.version.vid); } else { s.receipts.insert( diff --git a/crates/kc-cli/src/sync/mod.rs b/crates/kc-cli/src/sync/mod.rs index 0092a52..d728948 100644 --- a/crates/kc-cli/src/sync/mod.rs +++ b/crates/kc-cli/src/sync/mod.rs @@ -178,6 +178,17 @@ fn reserve( slot: &str, kind: SlotKind, snapshot: bool, +) -> Result { + reserve_keeping(ctx, s, slot, kind, snapshot, None) +} +/// Like `reserve`, but never evicts `keep`: the candidate whose acceptance needs the slot. +fn reserve_keeping( + ctx: &Ctx<'_, H>, + s: &mut State, + slot: &str, + kind: SlotKind, + snapshot: bool, + keep: Option<&str>, ) -> Result { if let Some(existing) = s.slots.get_mut(slot) { if kind > *existing { @@ -201,6 +212,9 @@ fn reserve( return Err(state_error()); } } + if let Some(keep) = keep { + budget.pin(keep); + } let result = if snapshot { budget.reserve_snapshot(slot) } else { @@ -220,10 +234,12 @@ fn reserve( .cloned() .collect::>(); s.candidates.retain(|_, c| c.version.slot != victim); - // Only the slots go: the vid binding stays, because the evicted candidate - // can be the one whose acceptance is reserving this slot. for c in evicted { s.gc.insert(c.base_record); + // An invalid binding's record belongs to the legitimate vid. + if !c.invalid_binding { + forget_binding(s, &c.version.name, c.version.vid); + } } s.slots.remove(&victim); s.gc.insert(victim); @@ -254,6 +270,74 @@ fn forget_binding(s: &mut State, name: &str, vid: Vid) { s.gc.insert(record_slot(name, vid)); } +/// A rejected offer stays blocked while its sender keeps retrying. +const REJECTED_OFFER_TTL: i64 = kc_wire::limits::INBOX_IDLE_DELETE_DAYS as i64 * 86400; +fn reject_offer(s: &mut State, delivery: String, now: i64) { + s.rejected_until + .insert(delivery.clone(), now.saturating_add(REJECTED_OFFER_TTL)); + s.rejected_offers.insert(delivery); +} +/// Whether an offer was rejected; a retry extends the block, so only silence expires it. +fn offer_rejected(s: &mut State, delivery: &str, now: i64) -> bool { + if !s.rejected_offers.contains(delivery) { + return false; + } + s.rejected_until + .insert(delivery.into(), now.saturating_add(REJECTED_OFFER_TTL)); + true +} +/// Expires silent rejected offers and drops bindings of offers that no longer have a +/// candidate. State written before expiries existed gets a full TTL on first prune. +fn prune(s: &mut State, now: i64) { + let rejected = std::mem::take(&mut s.rejected_offers); + let until = std::mem::take(&mut s.rejected_until); + for delivery in rejected { + let expiry = until + .get(&delivery) + .copied() + .unwrap_or_else(|| now.saturating_add(REJECTED_OFFER_TTL)); + if expiry >= now { + s.rejected_until.insert(delivery.clone(), expiry); + s.rejected_offers.insert(delivery); + } + } + // An unfinished transaction may still own a candidate's binding. + if s.journal.is_some() { + return; + } + for entry in std::mem::take(&mut s.unbound) { + let Some((name, vid)) = entry + .rsplit_once(':') + .and_then(|(name, hex)| Some((name.to_owned(), parse_vid(hex)?))) + else { + continue; + }; + s.unbound.insert(entry); + let candidate = s + .candidates + .values() + .any(|c| c.version.name == name && c.version.vid == vid); + // An accepted offer stays unbound until its sender's change arrives. + let accepted = s + .items + .get(&name) + .is_some_and(|i| i.head == vid || i.lineage.contains(&vid)); + if !candidate && !accepted { + forget_binding(s, &name, vid); + } + } +} +fn parse_vid(hex: &str) -> Option { + let mut vid = [0; 16]; + if hex.len() != 32 || !hex.is_ascii() { + return None; + } + for (byte, pair) in vid.iter_mut().zip(hex.as_bytes().chunks(2)) { + *byte = u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok()?; + } + Some(Vid(vid)) +} + fn release(s: &mut State, slot: &str) { if s.slots.get(slot) != Some(&SlotKind::Checkpoint) { s.slots.remove(slot); diff --git a/crates/kc-cli/src/sync/receive.rs b/crates/kc-cli/src/sync/receive.rs index fdbaf22..9413874 100644 --- a/crates/kc-cli/src/sync/receive.rs +++ b/crates/kc-cli/src/sync/receive.rs @@ -44,10 +44,11 @@ pub(crate) fn receive(ctx: &mut Ctx<'_, H>, peer: &str, message: &SyncM ctx, tr!("Ignored a stale sync offer for {name}.", name = name), )?; - } else if s - .rejected_offers - .contains(&delivery_key(peer, name, *known_generation, *vid)) - { + } else if offer_rejected( + &mut s, + &delivery_key(peer, name, *known_generation, *vid), + ctx.host.now(), + ) { // A rejected proposal is never resurrected by a transport retry. } else if lineage.len() <= 64 && value.expose().len() <= 200 * 1024 @@ -452,8 +453,12 @@ fn change_received( false, )? { result = AckResult::DeferredCapacity; - } else if category == CandidateKind::Conflict { - s.items.get_mut(name).unwrap().conflict = true; + } else { + if category == CandidateKind::Conflict { + s.items.get_mut(name).unwrap().conflict = true; + } + // Only a stored successor may retire the held change it supersedes. + transaction::retire_superseded(s, ctx.host.now()); } } Transition::Advance { diff --git a/crates/kc-cli/src/sync/state.rs b/crates/kc-cli/src/sync/state.rs index e2f758f..bf945bc 100644 --- a/crates/kc-cli/src/sync/state.rs +++ b/crates/kc-cli/src/sync/state.rs @@ -86,6 +86,9 @@ pub struct State { pub deferred: BTreeSet, #[serde(default)] pub rejected_offers: BTreeSet, + /// Expiry of each `rejected_offers` entry, kept apart so older versions still read it. + #[serde(default)] + pub rejected_until: BTreeMap, #[serde(default)] pub unbound: BTreeSet, pub items: BTreeMap, @@ -124,6 +127,7 @@ impl State { .map_err(|_| super::state_error()) } pub fn cleanup(&mut self, ctx: &Ctx<'_, H>) -> Result<()> { + super::prune(self, ctx.host.now()); // A binding scheduled for deletion may have become live again in the same // transaction (an accepted proposal evicted by its own checkpoint reservation). let live: BTreeSet = self diff --git a/crates/kc-cli/src/sync/transaction.rs b/crates/kc-cli/src/sync/transaction.rs index 8d2f6ca..919a958 100644 --- a/crates/kc-cli/src/sync/transaction.rs +++ b/crates/kc-cli/src/sync/transaction.rs @@ -99,18 +99,7 @@ fn prepare_local( new_vid: map::vid(vid), parents: parents.iter().copied().map(map::vid).collect(), snapshot_slot: slot.clone(), - targets: item - .scope - .iter() - .filter_map(|p| { - s.generations - .outgoing_generation(&PeerId(p.clone()), name) - .map(|generation| QueueTarget { - peer: PeerId(p.clone()), - generation, - }) - }) - .collect(), + targets: targets(s, name), }; let lineage = kc_sync::Lineage::new(item.lineage.iter().chain(&parents).copied().map(map::vid)) .with_head(map::vid(vid)) @@ -138,6 +127,22 @@ fn prepare_local( )?; Ok((record, version)) } +/// Scope devices which have accepted this item's current generation from us. +fn targets(s: &State, name: &str) -> Vec { + s.items.get(name).map_or_else(Vec::new, |item| { + item.scope + .iter() + .filter_map(|p| { + s.generations + .outgoing_generation(&PeerId(p.clone()), name) + .map(|generation| QueueTarget { + peer: PeerId(p.clone()), + generation, + }) + }) + .collect() + }) +} fn finish_local( ctx: &Ctx<'_, H>, s: &mut State, @@ -291,6 +296,7 @@ pub(crate) fn scan(ctx: &mut Ctx<'_, H>, s: &mut State) -> Result<()> { super::receive::preserve_mine(ctx, s, &name, &item)?; } } + retire_superseded(s, ctx.host.now()); s.cleanup(ctx) } fn scan_one(ctx: &mut Ctx<'_, H>, s: &mut State, name: &str) -> Result<()> { @@ -460,7 +466,14 @@ pub(super) fn accept(ctx: &mut Ctx<'_, H>, s: &mut State, c: &Candidate None }; if let Some(slot) = &checkpoint - && !reserve(ctx, s, slot, SlotKind::Checkpoint, false)? + && !reserve_keeping( + ctx, + s, + slot, + SlotKind::Checkpoint, + false, + Some(&c.version.slot), + )? { return Ok(false); } @@ -578,8 +591,105 @@ fn finish_remote( ); } clear_candidates(s, name); + if c.legacy { + publish_legacy(ctx, s, r, c)?; + } s.save(&ctx.state) } +/// A value accepted from a v1 sender is this device's own change: its vid was minted here +/// with the previous head as parent, so it goes to the scope like any local change (§2.8). +/// Idempotent for journal recovery, which reruns it only while the keychain holds the value. +fn publish_legacy( + ctx: &Ctx<'_, H>, + s: &mut State, + r: &RemoteJournalRecord, + c: &Candidate, +) -> Result<()> { + let name = &r.change_id.name; + let vid = c.version.vid; + let (value, kind, _) = current(ctx, name)?.ok_or_else(state_error)?; + s.items.get_mut(name).ok_or_else(state_error)?.own = true; + let slot = snapshot_slot(vid); + s.versions.insert( + vid_key(vid), + Version { + name: name.clone(), + vid, + parents: c.version.parents.clone(), + lineage: r.lineage.iter().copied().map(map::wire_vid).collect(), + kind, + slot: slot.clone(), + }, + ); + s.latest_local.insert(name.clone(), vid); + // The candidate slot was released just before, so this reservation is a net zero. + if !reserve(ctx, s, &slot, SlotKind::ConflictCandidate, true)? { + // The next digest's resend recreates the snapshot and queues the change. + return log( + ctx, + tr!("Sync storage is full; review pending items before retrying."), + ); + } + if ctx.store.get_internal(&slot)?.is_none() { + put_blob(ctx, &slot, kind, &value)?; + } + for target in targets(s, name) { + s.outbox.enqueue( + target.peer, + kc_sync::ChangeId { + name: name.clone(), + generation: target.generation, + new_vid: map::vid(vid), + }, + ); + } + Ok(()) +} +/// A later change from the same peer naming an open held candidate as a parent +/// supersedes it: that peer already replaced the value (§2.4). +pub(super) fn is_superseded(s: &State, old: &Candidate) -> bool { + old.category == CandidateKind::Held + && !old.invalid_binding + && !old.legacy + && !old.retire + && s.candidates.values().any(|new| { + // Parents are not authenticated: only the same peer may supersede its change. + new.peer == old.peer + && new.version.name == old.version.name + && new.generation == old.generation + && new.version.vid != old.version.vid + && !new.invalid_binding + && new.version.parents.contains(&old.version.vid) + }) +} +pub(super) fn retire_superseded(s: &mut State, now: i64) { + let keys: Vec<_> = s + .candidates + .iter() + .filter(|(_, c)| is_superseded(s, c)) + .map(|(k, _)| k.clone()) + .collect(); + for key in keys { + if let Some(old) = s.candidates.remove(&key) { + release(s, &old.version.slot); + s.gc.insert(old.base_record); + // The vid binding stays in known for the immutable-vid check. Held was already + // acknowledged, so no Rejected ACK is sent; the receipt stops a late duplicate. + s.receipts.insert( + delivery_key( + &old.peer, + &old.version.name, + old.generation, + old.version.vid, + ), + ( + kc_proto::sync::AckResult::Rejected, + now.saturating_add(3 * 86400), + ), + ); + } + } +} pub(super) fn queue(s: &mut State, peer: &str, message: Control) { // Coalesce metadata-only controls; messages never contain values or fingerprints. let encoded = serde_json::to_vec(&message).unwrap_or_default(); @@ -693,3 +803,54 @@ fn collect_orphan_snapshots(ctx: &Ctx<'_, H>, s: &mut State) -> Result< } Ok(()) } + +#[cfg(test)] +mod tests { + use super::{Candidate, CandidateKind, State, Version, Vid, is_superseded}; + + fn candidate(peer: &str, vid: u8, parents: &[u8], category: CandidateKind) -> Candidate { + Candidate { + peer: peer.into(), + version: Version { + name: "KEY".into(), + vid: Vid([vid; 16]), + parents: parents.iter().map(|p| Vid([*p; 16])).collect(), + lineage: vec![], + kind: kc_proto::sync::ItemKind::Text, + slot: format!("{peer}/{vid}"), + }, + generation: 1, + category, + base_head: None, + base_record: String::new(), + retire: false, + legacy: false, + invalid_binding: false, + } + } + fn with(candidates: &[&Candidate]) -> State { + let mut s = State::default(); + for c in candidates { + s.candidates.insert(c.version.slot.clone(), (*c).clone()); + } + s + } + + #[test] + fn is_superseded_requires_same_peer() { + let old = candidate("alpha", 1, &[0], CandidateKind::Held); + let successor = candidate("alpha", 2, &[1, 3], CandidateKind::Held); + assert!(is_superseded(&with(&[&old, &successor]), &old)); + assert!(!is_superseded(&with(&[&old]), &old)); + let forged = candidate("bravo", 2, &[1, 3], CandidateKind::Held); + assert!(!is_superseded(&with(&[&old, &forged]), &old)); + let conflict = candidate("alpha", 1, &[0], CandidateKind::Conflict); + assert!(!is_superseded(&with(&[&conflict, &successor]), &conflict)); + let mut legacy = old.clone(); + legacy.legacy = true; + assert!(!is_superseded(&with(&[&legacy, &successor]), &legacy)); + let mut stale = successor.clone(); + stale.generation = 2; + assert!(!is_superseded(&with(&[&old, &stale]), &old)); + } +} diff --git a/crates/kc-cli/tests/sync.rs b/crates/kc-cli/tests/sync.rs index 6b73641..f83161b 100644 --- a/crates/kc-cli/tests/sync.rs +++ b/crates/kc-cli/tests/sync.rs @@ -652,10 +652,12 @@ async fn legacy_overwrite_flag_and_code_receive_cannot_bypass_local_confirmation .expect(5); assert_eq!(state(&b)["candidates"].as_object().unwrap().len(), 1); assert_eq!(b.value("KEY").unwrap(), b"fake-initial-secret"); + // The accepted v1 value is this device's own change, queued for the sync scope. b.run(&["sync", "review"], human(vec![Answer::Select(0)])) .await - .expect(0); + .expect(8); assert_eq!(b.value("KEY").unwrap(), b"fake-legacy-terminal"); + assert!(outbox_has(&b, head(&b))); a.store() .set( "KEY", @@ -1057,7 +1059,9 @@ async fn legacy_policies_hold_and_denial_continues_batch_then_one_l_replaces() { human(vec![Answer::Yes]), ) .await; - out.expect(0); + // Pending only because the accepted v1 value is queued for the sync scope. + out.expect(8); + assert!(outbox_has(&b, head(&b))); assert_eq!( confirmations(&out), vec!["Replace KEY with the value from alpha"] @@ -1616,6 +1620,215 @@ async fn rejecting_proposal_deletes_binding_and_unbound_and_rm_releases_checkpoi assert_eq!(b.value("KEY").unwrap(), b"fake-initial-secret"); } +fn holds_candidate(s: &Value, vid: Vid) -> bool { + s["candidates"] + .as_object() + .unwrap() + .keys() + .any(|k| k.ends_with(&hex(&vid.0))) +} + +#[tokio::test] +async fn evicted_proposal_forgets_its_binding_and_unbound_entry() { + let (a, b, relay) = devices().await; + let mut offers = Vec::new(); + for n in 0..16 { + let name = format!("P{n}"); + let vid = Vid::random(); + post( + &a, + &b, + &relay, + offer_message(&name, vid, b"fake-eviction", 0), + ) + .await; + offers.push((name, vid)); + } + b.run(&["inbox"], Run::agent()).await.expect(8); + assert_eq!(state(&b)["unbound"].as_array().unwrap().len(), 16); + b.set("LOCAL", b"fake-local").await; + b.run(&["sync", "add", "LOCAL", "--peers", "alpha"], human(vec![])) + .await + .expect(8); + let after = state(&b); + let (evicted, kept): (Vec<_>, Vec<_>) = offers + .iter() + .partition(|(_, vid)| !holds_candidate(&after, *vid)); + assert_eq!(evicted.len(), 1); + let (name, vid) = evicted[0]; + assert!( + b.store() + .get_internal(&fp_slot(name, *vid)) + .unwrap() + .is_none() + ); + let unbound = after["unbound"].as_array().unwrap(); + assert_eq!(unbound.len(), 15); + assert!(!unbound.contains(&Value::from(format!("{name}:{}", hex(&vid.0))))); + for (name, vid) in kept { + assert!( + b.store() + .get_internal(&fp_slot(name, *vid)) + .unwrap() + .is_some() + ); + } +} + +#[tokio::test] +async fn accepting_a_proposal_at_capacity_does_not_evict_itself() { + let (a, b, relay) = devices().await; + // Not a sync item, so accepting the offer reserves a checkpoint for the local value. + b.set("TARGET", b"fake-target-local").await; + // The smallest slot name: the checkpoint reservation's first eviction choice. + let target = Vid([0; 16]); + post( + &a, + &b, + &relay, + offer_message("TARGET", target, b"fake-target-offer", 0), + ) + .await; + let mut others = Vec::new(); + for n in 1..16 { + let name = format!("P{n}"); + let vid = Vid::random(); + post( + &a, + &b, + &relay, + offer_message(&name, vid, b"fake-capacity", 0), + ) + .await; + others.push((name, vid)); + } + b.run(&["inbox"], Run::agent()).await.expect(8); + assert_eq!(state(&b)["candidates"].as_object().unwrap().len(), 16); + let mut answers = vec![Answer::Select(0)]; + answers.extend(std::iter::repeat_with(|| Answer::Select(2)).take(15)); + let out = b.run(&["sync", "review"], human(answers)).await; + out.expect(8); + assert!( + out.stderr.contains("Accepted TARGET from alpha."), + "{}", + out.stderr + ); + assert_eq!(b.value("TARGET").unwrap(), b"fake-target-offer"); + let s = state(&b); + let head: Vid = serde_json::from_value(s["items"]["TARGET"]["head"].clone()).unwrap(); + assert_eq!(head, target); + assert!( + b.store() + .get_internal(&fp_slot("TARGET", target)) + .unwrap() + .is_some() + ); + assert_eq!(s["candidates"].as_object().unwrap().len(), 14); + let evicted = others + .iter() + .filter(|(_, vid)| !holds_candidate(&s, *vid)) + .collect::>(); + assert_eq!(evicted.len(), 1); + let (name, vid) = evicted[0]; + assert!( + b.store() + .get_internal(&fp_slot(name, *vid)) + .unwrap() + .is_none() + ); +} + +#[tokio::test] +async fn rejected_offer_tombstone_slides_on_retry_and_expires_after_silence() { + let (a, b, relay) = devices().await; + let vid = Vid::random(); + let offer = || offer_message("PROPOSAL", vid, b"fake-tombstone", 0); + post(&a, &b, &relay, offer()).await; + b.run(&["inbox"], Run::agent()).await.expect(8); + b.run(&["sync", "review"], human(vec![Answer::Select(1)])) + .await + .expect(0); + let s = state(&b); + let key = s["rejected_offers"][0].as_str().unwrap().to_owned(); + let now = kc_proto::inbox::unix_now(); + assert!(s["rejected_until"][&key].as_i64().unwrap() > now); + let mut s = s; + s["rejected_until"][&key] = (now + 60).into(); + save_state(&b, &s); + post(&a, &b, &relay, offer()).await; + b.run(&["inbox"], Run::agent()).await.expect(0); + let s = state(&b); + assert!(s["candidates"].as_object().unwrap().is_empty()); + assert!(s["rejected_until"][&key].as_i64().unwrap() > now + 86400); + let mut s = s; + s["rejected_until"][&key] = 1.into(); + save_state(&b, &s); + b.run(&["sync"], Run::agent()).await.expect(0); + let s = state(&b); + assert!(s["rejected_offers"].as_array().unwrap().is_empty()); + assert!(s["rejected_until"].as_object().unwrap().is_empty()); + post(&a, &b, &relay, offer()).await; + b.run(&["inbox"], Run::agent()).await.expect(8); + assert!(holds_candidate(&state(&b), vid)); +} + +#[tokio::test] +async fn legacy_rejected_offer_array_state_still_loads() { + let (a, b, relay) = devices().await; + let vid = Vid::random(); + let offer = || offer_message("PROPOSAL", vid, b"fake-legacy-tombstone", 0); + post(&a, &b, &relay, offer()).await; + b.run(&["inbox"], Run::agent()).await.expect(8); + b.run(&["sync", "review"], human(vec![Answer::Select(1)])) + .await + .expect(0); + // State written before expiries existed: only the tombstone array. + let mut s = state(&b); + let key = s["rejected_offers"][0].as_str().unwrap().to_owned(); + s.as_object_mut().unwrap().remove("rejected_until"); + save_state(&b, &s); + b.run(&["sync"], Run::agent()).await.expect(0); + let s = state(&b); + // Older versions still read the array; the expiry lives beside it. + assert_eq!(s["rejected_offers"], Value::from(vec![key.clone()])); + assert!(s["rejected_until"][&key].as_i64().unwrap() > kc_proto::inbox::unix_now()); + post(&a, &b, &relay, offer()).await; + b.run(&["inbox"], Run::agent()).await.expect(0); + assert!(state(&b)["candidates"].as_object().unwrap().is_empty()); +} + +#[tokio::test] +async fn unbound_entry_without_candidate_is_swept() { + let (a, b, relay) = devices().await; + let vid = Vid::random(); + post( + &a, + &b, + &relay, + offer_message("PROPOSAL", vid, b"fake-unbound", 0), + ) + .await; + b.run(&["inbox"], Run::agent()).await.expect(8); + assert!( + b.store() + .get_internal(&fp_slot("PROPOSAL", vid)) + .unwrap() + .is_some() + ); + // A candidate dropped without its binding, as eviction did before. + let mut s = state(&b); + s["candidates"] = serde_json::json!({}); + save_state(&b, &s); + b.run(&["sync"], Run::agent()).await; + assert!(state(&b)["unbound"].as_array().unwrap().is_empty()); + assert!( + b.store() + .get_internal(&fp_slot("PROPOSAL", vid)) + .unwrap() + .is_none() + ); +} + #[tokio::test] async fn full_capacity_scan_and_preserve_mine_leave_inbox_review_and_resolve_operational() { let (a, b, relay) = devices().await; @@ -1680,3 +1893,166 @@ async fn full_capacity_scan_and_preserve_mine_leave_inbox_review_and_resolve_ope .expect(8); assert_eq!(state(&b)["items"]["KEY"]["conflict"], false); } + +fn outbox_has(d: &Device, vid: Vid) -> bool { + let wanted = serde_json::to_value(vid.0).unwrap(); + state(d)["outbox"]["deliveries"] + .as_array() + .unwrap() + .iter() + .flat_map(|peer| peer[1].as_array().unwrap().iter()) + .any(|entry| entry[0]["name"] == "KEY" && entry[0]["new_vid"] == wanted) +} +#[tokio::test] +async fn legacy_accept_is_published_to_sync_scope() { + let (a, b, _) = devices().await; + enroll(&a, &b).await; + a.store() + .set( + "KEY", + b"fake-legacy-published", + kc_store::ItemKind::Text, + kc_store::Origin::Local, + ) + .unwrap(); + a.run(&["send", "KEY", "--to", "bravo"], Run::agent()) + .await + .expect(0); + let out = b + .run( + &["inbox", "--on-conflict", "overwrite"], + human(vec![Answer::Yes]), + ) + .await; + assert!([0, 8].contains(&out.code), "{}", out.stderr); + assert_eq!(b.value("KEY").unwrap(), b"fake-legacy-published"); + let s = state(&b); + assert_eq!(s["items"]["KEY"]["own"], true); + let legacy_head = head(&b); + assert!(outbox_has(&b, legacy_head)); + assert!( + s["slots"] + .get(format!("sync/snapshot/{}", hex(&legacy_head.0))) + .is_some() + ); + pump(&a, &b).await; + assert_eq!(head(&a), head(&b)); + assert_eq!(a.value("KEY"), b.value("KEY")); + assert!(state(&a)["candidates"].as_object().unwrap().is_empty()); + assert!(state(&b)["candidates"].as_object().unwrap().is_empty()); +} +/// Alpha's held change X, then bravo's local change: alpha resolves the conflict, keeping +/// bravo's value, with a change naming X as a parent. Returns X's candidate key and record. +async fn superseded_setup(a: &Device, b: &Device) -> (String, Value) { + enroll(a, b).await; + a.set("KEY", b"fake-alpha-superseded").await; + pump(a, b).await; + let s = state(b); + let (key, held) = s["candidates"] + .as_object() + .unwrap() + .iter() + .next() + .map(|(k, v)| (k.clone(), v.clone())) + .unwrap(); + assert_eq!(held["category"], "held"); + b.set("KEY", b"fake-bravo-kept").await; + pump(a, b).await; + assert_eq!(state(a)["items"]["KEY"]["conflict"], true); + (key, held) +} +#[tokio::test] +async fn review_skips_held_change_superseded_by_same_peer_resolve() { + let (a, b, _) = devices().await; + let (key, held) = superseded_setup(&a, &b).await; + a.run( + &["sync", "resolve", "KEY", "--keep", "bravo"], + human(vec![]), + ) + .await + .expect(8); + pump(&a, &b).await; + let s = state(&b); + let candidates = s["candidates"].as_object().unwrap(); + assert_eq!(candidates.len(), 1, "{candidates:?}"); + assert!(!candidates.contains_key(&key)); + assert!(s["slots"].get(&key).is_none()); + assert!(b.store().get_internal(&key).unwrap().is_none()); + let base = held["base_record"].as_str().unwrap(); + assert!(b.store().get_internal(base).unwrap().is_none()); + b.run(&["sync", "review"], human(vec![Answer::Select(0)])) + .await + .expect(0); + pump(&a, &b).await; + assert_eq!(head(&a), head(&b)); + assert_eq!(a.value("KEY"), b.value("KEY")); + assert_eq!(b.value("KEY").unwrap(), b"fake-bravo-kept"); +} +#[tokio::test] +async fn superseded_held_survives_when_new_candidate_is_capacity_deferred() { + let (a, b, _) = devices().await; + let (key, _) = superseded_setup(&a, &b).await; + let mut s = state(&b); + for n in 0..16 { + let slot = format!("sync/kg/test-{n}"); + b.store().set_internal(&slot, b"fake-pinned").unwrap(); + s["slots"][slot] = "Checkpoint".into(); + } + save_state(&b, &s); + a.run( + &["sync", "resolve", "KEY", "--keep", "bravo"], + human(vec![]), + ) + .await + .expect(8); + pump(&a, &b).await; + let s = state(&b); + let candidates = s["candidates"].as_object().unwrap(); + assert_eq!(candidates.len(), 1, "{candidates:?}"); + assert!(candidates.contains_key(&key)); + assert!(b.store().get_internal(&key).unwrap().is_some()); +} +#[tokio::test] +async fn retired_superseded_vid_is_not_resurrected_by_duplicate_delivery() { + let (a, b, relay) = devices().await; + let (key, held) = superseded_setup(&a, &b).await; + a.run( + &["sync", "resolve", "KEY", "--keep", "bravo"], + human(vec![]), + ) + .await + .expect(8); + pump(&a, &b).await; + assert!( + !state(&b)["candidates"] + .as_object() + .unwrap() + .contains_key(&key) + ); + let version = &held["version"]; + post( + &a, + &b, + &relay, + SyncMsg::Changes { + changes: vec![Change { + name: ItemName::new("KEY").unwrap(), + generation: held["generation"].as_u64().unwrap(), + new_vid: serde_json::from_value(version["vid"].clone()).unwrap(), + parents: serde_json::from_value(version["parents"].clone()).unwrap(), + lineage: serde_json::from_value(version["lineage"].clone()).unwrap(), + op: Op::Put { + kind: kc_proto::sync::ItemKind::Text, + value: SecretBytes::from_slice(b"fake-alpha-superseded"), + }, + approval_ref: None, + }], + }, + ) + .await; + b.run(&["inbox"], Run::agent()).await.expect(8); + let s = state(&b); + let candidates = s["candidates"].as_object().unwrap(); + assert_eq!(candidates.len(), 1, "{candidates:?}"); + assert!(!candidates.contains_key(&key)); +} diff --git a/crates/kc-sync/src/slots.rs b/crates/kc-sync/src/slots.rs index cfe9b90..bf41779 100644 --- a/crates/kc-sync/src/slots.rs +++ b/crates/kc-sync/src/slots.rs @@ -105,6 +105,11 @@ impl SlotBudget { result } + /// Protects an in-use reservation from eviction during this reservation (§12.3). + pub fn pin(&mut self, name: &str) { + self.pinned_snapshots.insert(name.into()); + } + /// Releases resolved/rejected slots or finally acknowledged snapshots, never checkpoints (§12.3). pub fn release(&mut self, name: &str) -> bool { if self.slots.get(name) == Some(&SlotKind::Checkpoint) { diff --git a/docs/design/sync.md b/docs/design/sync.md index c060779..1c75a42 100644 --- a/docs/design/sync.md +++ b/docs/design/sync.md @@ -113,7 +113,7 @@ | 승인자 추가 | L + 기존 승인자의 A+ | 각 기기에서 L 로 지문 확인 후 고정 | | 승인자 제거 | L | — (마지막 승인자를 지우면 덮어쓰기는 전부 보류. 새 등록은 각 기기 L 확인 필요) | -**기존 명령도 같은 규칙을 따른다**(codex P1-8). 동기화 대상 항목을 `kc inbox --on-conflict overwrite`·`kc receive`·v1 인박스 메시지로 덮어쓰려 하면 sync 정책으로 보낸다. 승인 서명이 없으면 L 이 필요하고, 비대화형이면 보류한다. +**기존 명령도 같은 규칙을 따른다**(codex P1-8). 동기화 대상 항목을 `kc inbox --on-conflict overwrite`·`kc receive`·v1 인박스 메시지로 덮어쓰려 하면 sync 정책으로 보낸다. 승인 서명이 없으면 L 이 필요하고, 비대화형이면 보류한다. L 로 받아들인 값은 이 기기의 로컬 변경으로 기록하고(새 vid, parent = 받기 전 head) 범위 기기에 보낸다. v1 로 보낸 기기를 범위에 넣지는 않는다. 에이전트는 L·A·A+ 어느 것도 통과하지 못한다. 할 수 있는 최대치는 승인 요청을 올리는 것과 제안을 보내는 것이다. From 4a25d52e77c1a95b3f281b4a983c103ae2278357 Mon Sep 17 00:00:00 2001 From: seunghan Kim Date: Wed, 14 Oct 2026 09:07:59 +0900 Subject: [PATCH 3/4] =?UTF-8?q?fix(sync):=20=EC=88=9C=EC=84=9C=20=EB=92=A4?= =?UTF-8?q?=EB=B0=94=EB=80=90=20=EC=A0=84=EB=8B=AC=EC=97=90=EC=84=9C=20?= =?UTF-8?q?=ED=87=B4=EC=97=AD=20=EA=B8=B0=EB=A1=9D=20=EB=B3=B4=EC=A1=B4?= =?UTF-8?q?=C2=B7=EC=8B=A4=ED=8C=A8=ED=95=9C=20=EC=88=98=EB=9D=BD=C2=B7?= =?UTF-8?q?=ED=95=B4=EA=B2=B0=EC=97=90=20=EC=84=B1=EA=B3=B5=20=EB=AC=B8?= =?UTF-8?q?=EA=B5=AC=20=EA=B8=88=EC=A7=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 후속 변경이 먼저 와 즉시 퇴역한 보류분의 Rejected receipt 를 Held 로 덮지 않음 - accept() 결과를 Applied/Conflict/Unsettled/Full 로 나눠 review 문구를 실제 결과에 맞춤 - resolve_value() 가 용량 부족이면 false 를 돌려 성공 문구 대신 저장 공간 안내 Refs DCO-40 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AcJNLuNvFR9uo8NsqLVCj6 --- crates/kc-cli/locales/de.toml | 1 + crates/kc-cli/locales/es.toml | 1 + crates/kc-cli/locales/fr.toml | 1 + crates/kc-cli/locales/ja.toml | 1 + crates/kc-cli/locales/ko.toml | 1 + crates/kc-cli/locales/zh-Hans.toml | 1 + crates/kc-cli/locales/zh-Hant.toml | 1 + crates/kc-cli/src/sync/actions.rs | 45 +++++++---- crates/kc-cli/src/sync/receive.rs | 9 ++- crates/kc-cli/src/sync/transaction.rs | 38 +++++++--- crates/kc-cli/tests/sync.rs | 104 +++++++++++++++++++++++++- 11 files changed, 176 insertions(+), 27 deletions(-) diff --git a/crates/kc-cli/locales/de.toml b/crates/kc-cli/locales/de.toml index 48f3f9d..6ceb88b 100644 --- a/crates/kc-cli/locales/de.toml +++ b/crates/kc-cli/locales/de.toml @@ -500,6 +500,7 @@ "Ignored a sync offer from disabled or blocked peer {peer}." = "Synchronisierungsangebot vom deaktivierten oder blockierten Gerät {peer} ignoriert." "Sync item held; run `kc sync review`." = "Synchronisierungselement zurückgehalten; `kc sync review` ausführen." "{name} is in conflict; settle it with `kc sync resolve {name}` first." = "{name} steht im Konflikt; zuerst mit `kc sync resolve {name}` auflösen." +"{name} changed on this device meanwhile and is now a conflict; settle it with `kc sync resolve {name}`." = "{name} wurde inzwischen auf diesem Gerät geändert und steht jetzt im Konflikt; mit `kc sync resolve {name}` auflösen." "removed from sync" = "aus der Synchronisierung entfernt" "hasn't answered the sync handshake yet" = "hat auf den Sync-Handshake noch nicht geantwortet" "paused after too many changes" = "nach zu vielen Änderungen pausiert" diff --git a/crates/kc-cli/locales/es.toml b/crates/kc-cli/locales/es.toml index 2fda5c5..e92fd2c 100644 --- a/crates/kc-cli/locales/es.toml +++ b/crates/kc-cli/locales/es.toml @@ -500,6 +500,7 @@ "Ignored a sync offer from disabled or blocked peer {peer}." = "Se ignoró una oferta de sincronización del dispositivo desactivado o bloqueado {peer}." "Sync item held; run `kc sync review`." = "Elemento de sincronización retenido; ejecuta `kc sync review`." "{name} is in conflict; settle it with `kc sync resolve {name}` first." = "{name} está en conflicto; resuélvelo primero con `kc sync resolve {name}`." +"{name} changed on this device meanwhile and is now a conflict; settle it with `kc sync resolve {name}`." = "{name} cambió en este dispositivo mientras tanto y ahora está en conflicto; resuélvelo con `kc sync resolve {name}`." "removed from sync" = "quitado de la sincronización" "hasn't answered the sync handshake yet" = "aún no ha respondido al saludo de sincronización" "paused after too many changes" = "en pausa tras demasiados cambios" diff --git a/crates/kc-cli/locales/fr.toml b/crates/kc-cli/locales/fr.toml index f7ba5e9..8943b10 100644 --- a/crates/kc-cli/locales/fr.toml +++ b/crates/kc-cli/locales/fr.toml @@ -500,6 +500,7 @@ "Ignored a sync offer from disabled or blocked peer {peer}." = "Offre de synchronisation ignorée : appareil {peer} désactivé ou bloqué." "Sync item held; run `kc sync review`." = "Élément de synchronisation en attente ; exécutez `kc sync review`." "{name} is in conflict; settle it with `kc sync resolve {name}` first." = "{name} est en conflit ; résolvez-le d’abord avec `kc sync resolve {name}`." +"{name} changed on this device meanwhile and is now a conflict; settle it with `kc sync resolve {name}`." = "{name} a été modifié entre-temps sur cet appareil et est maintenant en conflit ; résolvez-le avec `kc sync resolve {name}`." "removed from sync" = "retiré de la synchronisation" "hasn't answered the sync handshake yet" = "n’a pas encore répondu à la négociation de synchronisation" "paused after too many changes" = "en pause après trop de modifications" diff --git a/crates/kc-cli/locales/ja.toml b/crates/kc-cli/locales/ja.toml index 3bc49b3..d964252 100644 --- a/crates/kc-cli/locales/ja.toml +++ b/crates/kc-cli/locales/ja.toml @@ -500,6 +500,7 @@ "Ignored a sync offer from disabled or blocked peer {peer}." = "無効またはブロックされたデバイス{peer}からの同期提案を無視しました。" "Sync item held; run `kc sync review`." = "同期項目を保留しました。`kc sync review`を実行してください。" "{name} is in conflict; settle it with `kc sync resolve {name}` first." = "{name} は競合中です。先に `kc sync resolve {name}` で解決してください。" +"{name} changed on this device meanwhile and is now a conflict; settle it with `kc sync resolve {name}`." = "その間にこのデバイスで {name} が変更されたため、競合になりました。`kc sync resolve {name}` で解決してください。" "removed from sync" = "同期から外した" "hasn't answered the sync handshake yet" = "同期ハンドシェイクの応答待ち" "paused after too many changes" = "変更が多すぎるため一時停止中" diff --git a/crates/kc-cli/locales/ko.toml b/crates/kc-cli/locales/ko.toml index b6397dd..ed53b24 100644 --- a/crates/kc-cli/locales/ko.toml +++ b/crates/kc-cli/locales/ko.toml @@ -500,6 +500,7 @@ "Ignored a sync offer from disabled or blocked peer {peer}." = "비활성화되거나 차단된 기기 {peer}의 동기화 제안을 무시했습니다." "Sync item held; run `kc sync review`." = "동기화 항목을 보류했습니다. `kc sync review`를 실행하세요." "{name} is in conflict; settle it with `kc sync resolve {name}` first." = "{name} 항목이 충돌 중입니다. 먼저 `kc sync resolve {name}`로 해결하세요." +"{name} changed on this device meanwhile and is now a conflict; settle it with `kc sync resolve {name}`." = "그사이 이 기기에서 {name} 항목이 바뀌어 충돌 상태가 되었습니다. `kc sync resolve {name}`로 해결하세요." "removed from sync" = "동기화에서 뺌" "hasn't answered the sync handshake yet" = "아직 동기화 연결 응답 없음" "paused after too many changes" = "변경이 너무 많아 일시 중지됨" diff --git a/crates/kc-cli/locales/zh-Hans.toml b/crates/kc-cli/locales/zh-Hans.toml index 7bfb09c..d369a53 100644 --- a/crates/kc-cli/locales/zh-Hans.toml +++ b/crates/kc-cli/locales/zh-Hans.toml @@ -500,6 +500,7 @@ "Ignored a sync offer from disabled or blocked peer {peer}." = "已忽略已禁用或被阻止的设备{peer}的同步提议。" "Sync item held; run `kc sync review`." = "同步项目已保留;请运行 `kc sync review`。" "{name} is in conflict; settle it with `kc sync resolve {name}` first." = "{name} 存在冲突,请先用 `kc sync resolve {name}` 解决。" +"{name} changed on this device meanwhile and is now a conflict; settle it with `kc sync resolve {name}`." = "{name} 在此期间已在本设备上更改,现已成为冲突,请用 `kc sync resolve {name}` 解决。" "removed from sync" = "已移出同步" "hasn't answered the sync handshake yet" = "尚未回应同步握手" "paused after too many changes" = "因更改过多已暂停" diff --git a/crates/kc-cli/locales/zh-Hant.toml b/crates/kc-cli/locales/zh-Hant.toml index 3d564d1..ff1cbcb 100644 --- a/crates/kc-cli/locales/zh-Hant.toml +++ b/crates/kc-cli/locales/zh-Hant.toml @@ -500,6 +500,7 @@ "Ignored a sync offer from disabled or blocked peer {peer}." = "已忽略已停用或遭封鎖的裝置{peer}的同步提議。" "Sync item held; run `kc sync review`." = "同步項目已保留;請執行 `kc sync review`。" "{name} is in conflict; settle it with `kc sync resolve {name}` first." = "{name} 有衝突,請先用 `kc sync resolve {name}` 解決。" +"{name} changed on this device meanwhile and is now a conflict; settle it with `kc sync resolve {name}`." = "{name} 在此期間已在本裝置上變更,現已成為衝突,請用 `kc sync resolve {name}` 解決。" "removed from sync" = "已移出同步" "hasn't answered the sync handshake yet" = "尚未回應同步交握" "paused after too many changes" = "因變更過多已暫停" diff --git a/crates/kc-cli/src/sync/actions.rs b/crates/kc-cli/src/sync/actions.rs index 7a55e3d..dff5a5d 100644 --- a/crates/kc-cli/src/sync/actions.rs +++ b/crates/kc-cli/src/sync/actions.rs @@ -1,7 +1,7 @@ use super::*; use crate::cli::{SyncCommand, SyncPeerCommand}; use state::{CandidateKind, Control, Item, Offer, Peer}; -use transaction::{blob, put_blob, queue}; +use transaction::{Accepted, blob, put_blob, queue}; pub(crate) fn label(ctx: &Ctx<'_, H>, peer: &str) -> Result { if peer == "mine" { @@ -454,12 +454,22 @@ pub(crate) fn review(ctx: &mut Ctx<'_, H>) -> Result { if let Some(current) = s.candidates.get(&c.version.slot).cloned() && current.category != CandidateKind::Conflict { - transaction::accept(ctx, &mut s, ¤t)?; - done.push(tr!( - "Accepted {name} from {peer}.", - name = c.version.name, - peer = label(ctx, &c.peer)? - )); + match transaction::accept(ctx, &mut s, ¤t)? { + Accepted::Applied => done.push(tr!( + "Accepted {name} from {peer}.", + name = c.version.name, + peer = label(ctx, &c.peer)? + )), + Accepted::Conflict => done.push(tr!( + "{name} changed on this device meanwhile and is now a conflict; settle it with `kc sync resolve {name}`.", + name = c.version.name + )), + // accept() already said which conflict must be settled first. + Accepted::Unsettled => {} + Accepted::Full => done.push(tr!( + "Sync storage is full; review pending items before retrying." + )), + } } } s.cleanup(ctx)?; @@ -646,7 +656,11 @@ pub(crate) fn command(ctx: &mut Ctx<'_, H>, mut command: SyncCommand) - return Err(state_error()); } let value = blob(ctx, &checkpoint_slot(&name))?; - transaction::resolve_value(ctx, &mut s, &name, value.value.expose(), value.kind)?; + if !transaction::resolve_value(ctx, &mut s, &name, value.value.expose(), value.kind)? { + done.push(tr!( + "Sync storage is full; review pending items before retrying." + )); + } } SyncCommand::Resolve { name, keep } => { scan(ctx, &mut s)?; @@ -720,12 +734,15 @@ pub(crate) fn command(ctx: &mut Ctx<'_, H>, mut command: SyncCommand) - let value = blob(ctx, &c.version.slot)?; (Zeroizing::new(value.value.expose().to_vec()), value.kind) }; - transaction::resolve_value(ctx, &mut s, &name, &value, kind)?; - done.push(tr!( - "Resolved {name}, keeping {choice}; the other devices review it with `kc sync review`.", - name = name, - choice = choice - )); + done.push(if transaction::resolve_value(ctx, &mut s, &name, &value, kind)? { + tr!( + "Resolved {name}, keeping {choice}; the other devices review it with `kc sync review`.", + name = name, + choice = choice + ) + } else { + tr!("Sync storage is full; review pending items before retrying.") + }); } SyncCommand::Peer { command } => match command { SyncPeerCommand::List => { diff --git a/crates/kc-cli/src/sync/receive.rs b/crates/kc-cli/src/sync/receive.rs index 9413874..819c9a3 100644 --- a/crates/kc-cli/src/sync/receive.rs +++ b/crates/kc-cli/src/sync/receive.rs @@ -423,6 +423,7 @@ fn change_received( .insert(name.into()); } let mut result = map::wire_ack(decision.ack); + let mut retired = false; match decision.transition { Transition::Hold { .. } | Transition::Conflict { .. } => { let category = if result == AckResult::Conflict { @@ -459,6 +460,10 @@ fn change_received( } // Only a stored successor may retire the held change it supersedes. transaction::retire_superseded(s, ctx.host.now()); + // Reordered delivery: the successor arrived first, so this change retired + // at once. Its Rejected receipt must stand; the ACK stays Held, as in order. + // A Rejected receipt returned early above, so here only retirement wrote it. + retired = matches!(s.receipts.get(&delivery), Some((AckResult::Rejected, _))); } } Transition::Advance { @@ -508,7 +513,7 @@ fn change_received( // No verified approval is ever constructed in Phase 1. _ => return Err(state_error()), } - if result != AckResult::DeferredCapacity { + if result != AckResult::DeferredCapacity && !retired { s.receipts .insert(delivery, (result, ctx.host.now().saturating_add(3 * 86400))); } @@ -770,7 +775,7 @@ pub(crate) fn legacy( return Err(error); } let c = s.candidates[&slot].clone(); - if transaction::accept(ctx, &mut s, &c)? { + if transaction::accept(ctx, &mut s, &c)? == transaction::Accepted::Applied { return Ok(Some(kc_proto::ItemStatus::Stored)); } } diff --git a/crates/kc-cli/src/sync/transaction.rs b/crates/kc-cli/src/sync/transaction.rs index 919a958..4785e6a 100644 --- a/crates/kc-cli/src/sync/transaction.rs +++ b/crates/kc-cli/src/sync/transaction.rs @@ -363,19 +363,20 @@ pub(super) fn publish_current( finish_local(ctx, s, &r, &v, false)?; clear_intent(ctx, s) } +/// Returns false when sync storage is full and nothing was resolved. pub(super) fn resolve_value( ctx: &mut Ctx<'_, H>, s: &mut State, name: &str, value: &[u8], kind: ItemKind, -) -> Result<()> { +) -> Result { let item = &s.items[name]; if !item.conflict && !s.candidates.values().any(|c| c.version.name == name) && current(ctx, name)?.is_some_and(|v| v.1 == kind && v.0.as_slice() == value) { - return Ok(()); + return Ok(true); } let mut parents = vec![item.head]; parents.extend( @@ -394,7 +395,8 @@ pub(super) fn resolve_value( ctx, tr!("Sync storage is full; review pending items before retrying."), )?; - return s.save(&ctx.state); + s.save(&ctx.state)?; + return Ok(false); } Err(error) => return Err(error), }; @@ -402,9 +404,25 @@ pub(super) fn resolve_value( interrupted(ctx)?; put_blob(ctx, &v.slot, kind, value)?; finish_local(ctx, s, &r, &v, true)?; - clear_intent(ctx, s) + clear_intent(ctx, s)?; + Ok(true) } -pub(super) fn accept(ctx: &mut Ctx<'_, H>, s: &mut State, c: &Candidate) -> Result { +/// What `accept` did with a candidate, so callers report only what happened. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum Accepted { + Applied, + /// The value or head changed here since receipt; the candidate is now a conflict. + Conflict, + /// The item is in conflict and this candidate does not settle it (already reported). + Unsettled, + /// No room for the checkpoint; sync storage is full. + Full, +} +pub(super) fn accept( + ctx: &mut Ctx<'_, H>, + s: &mut State, + c: &Candidate, +) -> Result { let name = &c.version.name; let now = current(ctx, name)?; let actual = now.as_ref().map_or(Fp([0; 32]), |v| v.2); @@ -424,7 +442,7 @@ pub(super) fn accept(ctx: &mut Ctx<'_, H>, s: &mut State, c: &Candidate item.conflict = true; } s.save(&ctx.state)?; - return Ok(false); + return Ok(Accepted::Conflict); } // While the item is in conflict, only `kc sync resolve` may settle it: accepting a // proposal or held change here would drop the other candidates (§2.4). @@ -452,11 +470,11 @@ pub(super) fn accept(ctx: &mut Ctx<'_, H>, s: &mut State, c: &Candidate name = name ) ); - return Ok(false); + return Ok(Accepted::Unsettled); } if c.retire { super::actions::remove(ctx, s, name)?; - return Ok(true); + return Ok(Accepted::Applied); } let value = blob(ctx, &c.version.slot)?; let fp = fingerprint(ctx, name, value.kind, value.value.expose())?; @@ -475,7 +493,7 @@ pub(super) fn accept(ctx: &mut Ctx<'_, H>, s: &mut State, c: &Candidate Some(&c.version.slot), )? { - return Ok(false); + return Ok(Accepted::Full); } let lineage = kc_sync::Lineage::new(c.version.lineage.iter().copied().chain(head).map(map::vid)) @@ -521,7 +539,7 @@ pub(super) fn accept(ctx: &mut Ctx<'_, H>, s: &mut State, c: &Candidate interrupted(ctx)?; finish_remote(ctx, s, &r, c)?; clear_intent(ctx, s)?; - Ok(true) + Ok(Accepted::Applied) } fn finish_remote( ctx: &Ctx<'_, H>, diff --git a/crates/kc-cli/tests/sync.rs b/crates/kc-cli/tests/sync.rs index f83161b..f25dd72 100644 --- a/crates/kc-cli/tests/sync.rs +++ b/crates/kc-cli/tests/sync.rs @@ -1879,7 +1879,13 @@ async fn full_capacity_scan_and_preserve_mine_leave_inbox_review_and_resolve_ope .run(&["sync", "resolve", "KEY", "--keep", "mine"], human(vec![])) .await; out.expect(8); - assert!(!out.stderr.contains("Sync storage is full")); + // Resolve says why nothing was resolved instead of claiming success. + assert!( + out.stderr.contains("Sync storage is full"), + "{}", + out.stderr + ); + assert!(!out.stderr.contains("Resolved KEY"), "{}", out.stderr); assert_eq!(b.value("KEY").unwrap(), b"fake-out-of-band"); // After capacity is freed, the same review/resolve path can recover normally. let mut s = state(&b); @@ -2056,3 +2062,99 @@ async fn retired_superseded_vid_is_not_resurrected_by_duplicate_delivery() { assert_eq!(candidates.len(), 1, "{candidates:?}"); assert!(!candidates.contains_key(&key)); } +#[tokio::test] +async fn reordered_superseded_held_change_stays_retired_after_successor_is_rejected() { + let (a, b, relay) = devices().await; + enroll(&a, &b).await; + let base = head(&b); + let (x, z) = (Vid::random(), Vid::random()); + let change = |vid: Vid, parents: Vec, value: &[u8]| SyncMsg::Changes { + changes: vec![Change { + name: ItemName::new("KEY").unwrap(), + generation: 1, + new_vid: vid, + lineage: parents.iter().copied().chain([vid]).collect(), + parents, + op: Op::Put { + kind: kc_proto::sync::ItemKind::Text, + value: SecretBytes::from_slice(value), + }, + approval_ref: None, + }], + }; + let superseded = change(x, vec![base], b"fake-reordered-x"); + // The successor Z, naming X as a parent, arrives first. + post( + &a, + &b, + &relay, + change(z, vec![base, x], b"fake-reordered-z"), + ) + .await; + b.run(&["inbox"], Run::agent()).await.expect(8); + post(&a, &b, &relay, superseded.clone()).await; + b.run(&["inbox"], Run::agent()).await.expect(8); + let s = state(&b); + let candidates = s["candidates"].as_object().unwrap(); + assert_eq!(candidates.len(), 1, "{candidates:?}"); + assert!(candidates.keys().all(|k| k.ends_with(&hex(&z.0)))); + b.run(&["sync", "review"], human(vec![Answer::Select(1)])) + .await + .expect(0); + post(&a, &b, &relay, superseded).await; + b.run(&["inbox"], Run::agent()).await.expect(0); + assert!(state(&b)["candidates"].as_object().unwrap().is_empty()); + assert_eq!(b.value("KEY").unwrap(), b"fake-initial-secret"); +} +#[tokio::test] +async fn review_accept_after_local_edit_reports_conflict_instead_of_accepted() { + let (a, b, _) = devices().await; + enroll(&a, &b).await; + a.set("KEY", b"fake-incoming").await; + pump(&a, &b).await; + b.set("KEY", b"fake-intervening-local").await; + let out = b + .run(&["sync", "review"], human(vec![Answer::Select(0)])) + .await; + out.expect(8); + assert!(!out.stderr.contains("Accepted KEY"), "{}", out.stderr); + assert!( + out.stderr + .contains("KEY changed on this device meanwhile and is now a conflict"), + "{}", + out.stderr + ); + assert_eq!(b.value("KEY").unwrap(), b"fake-intervening-local"); +} +#[tokio::test] +async fn resolve_at_full_capacity_reports_storage_full_instead_of_resolved() { + let (a, b, _) = devices().await; + enroll(&a, &b).await; + let mut s = state(&b); + for n in 0..16 { + let slot = format!("sync/kg/test-{n}"); + b.store().set_internal(&slot, b"fake-pinned").unwrap(); + s["slots"][slot] = "Checkpoint".into(); + } + save_state(&b, &s); + b.store() + .set( + "KEY", + b"fake-out-of-band", + kc_store::ItemKind::Text, + kc_store::Origin::Local, + ) + .unwrap(); + let out = b + .run(&["sync", "resolve", "KEY", "--keep", "mine"], human(vec![])) + .await; + out.expect(8); + assert!(!out.stderr.contains("Resolved KEY"), "{}", out.stderr); + assert!( + out.stderr + .contains("Sync storage is full; review pending items before retrying."), + "{}", + out.stderr + ); + assert_eq!(state(&b)["items"]["KEY"]["conflict"], true); +} From 335c1cf2bf76c233313c5d67eaf2b6ba87f6e355 Mon Sep 17 00:00:00 2001 From: seunghan Kim Date: Wed, 14 Oct 2026 09:19:07 +0900 Subject: [PATCH 4/4] =?UTF-8?q?release:=20v0.3.1=20=EB=A1=9C=20=EB=B2=84?= =?UTF-8?q?=EC=A0=84=20=EC=98=AC=EB=A6=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs DCO-40 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AcJNLuNvFR9uo8NsqLVCj6 --- Cargo.lock | 12 ++++++------ Cargo.toml | 10 +++++----- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 50fb81c..a103644 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1496,7 +1496,7 @@ dependencies = [ [[package]] name = "kc-cli" -version = "0.3.0" +version = "0.3.1" dependencies = [ "base64 0.22.1", "block2", @@ -1535,7 +1535,7 @@ dependencies = [ [[package]] name = "kc-proto" -version = "0.3.0" +version = "0.3.1" dependencies = [ "base64 0.22.1", "chacha20poly1305", @@ -1558,7 +1558,7 @@ dependencies = [ [[package]] name = "kc-relay" -version = "0.3.0" +version = "0.3.1" dependencies = [ "anyhow", "axum", @@ -1586,7 +1586,7 @@ dependencies = [ [[package]] name = "kc-store" -version = "0.3.0" +version = "0.3.1" dependencies = [ "apple-native-keyring-store", "directories", @@ -1610,7 +1610,7 @@ dependencies = [ [[package]] name = "kc-sync" -version = "0.3.0" +version = "0.3.1" dependencies = [ "rand", "serde", @@ -1620,7 +1620,7 @@ dependencies = [ [[package]] name = "kc-wire" -version = "0.3.0" +version = "0.3.1" dependencies = [ "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index dabfd75..84443cc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/kc-wire", "crates/kc-proto", "crates/kc-store", "crates/kc-relay", "crates/kc-cli", "crates/kc-sync"] [workspace.package] -version = "0.3.0" +version = "0.3.1" edition = "2024" rust-version = "1.88" license = "MIT" @@ -15,10 +15,10 @@ authors = ["Dcode "] # `dep = { workspace = true, features = [...] }`. A lane that needs a crate that # isn't listed here may add it to its own Cargo.toml directly. [workspace.dependencies] -kc-wire = { path = "crates/kc-wire", version = "0.3.0" } -kc-proto = { path = "crates/kc-proto", version = "0.3.0" } -kc-store = { path = "crates/kc-store", version = "0.3.0" } -kc-sync = { path = "crates/kc-sync", version = "0.3.0" } +kc-wire = { path = "crates/kc-wire", version = "0.3.1" } +kc-proto = { path = "crates/kc-proto", version = "0.3.1" } +kc-store = { path = "crates/kc-store", version = "0.3.1" } +kc-sync = { path = "crates/kc-sync", version = "0.3.1" } anyhow = "1" thiserror = "2"