Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(config-sync): add explicit append-only WebDAV mode

vastsa1c1a3f525b0d
diff --git a/apps/desktop/src/components/settings/ConfigSyncPage.tsx b/apps/desktop/src/components/settings/ConfigSyncPage.tsx
index 188a21704..1ef776277 100644
--- a/apps/desktop/src/components/settings/ConfigSyncPage.tsx
+++ b/apps/desktop/src/components/settings/ConfigSyncPage.tsx
@@ -5,12 +5,14 @@ import type {
ConfigSyncCategorySelection,
ConfigSyncHistoryEntry,
ConfigSyncPendingApproval,
+ ConfigSyncRemoteMode,
ConfigSyncState,
} from "@pi-desktop/shared";
import { api } from "../../lib/api";
import { Badge, Button, Field, Input, PasswordInput, cx } from "../ui";
import { IconCloudDown, IconRefresh, IconShield, IconTrash } from "../icons";
import { SettingsCard, SettingsRow } from "../../features/settings/primitives";
+import { SettingsMenuSelect } from "./SettingsMenuSelect";
const CATEGORIES: Array<{
id: Exclude<ConfigSyncCategory, "credentials" | "memory">;
@@ -86,12 +88,14 @@ export function ConfigSyncPage() {
const [selection, setSelection] =
useState<ConfigSyncCategorySelection>(DEFAULT_SELECTION);
const [allowInsecureHttp, setAllowInsecureHttp] = useState(false);
+ const [remoteMode, setRemoteMode] = useState<ConfigSyncRemoteMode>("strict");
const refresh = useCallback(async () => {
try {
const next = await api.configSyncGetState();
setState(next);
setAllowInsecureHttp(next.allowInsecureHttp === true);
+ setRemoteMode(next.remoteMode ?? "strict");
if (next.configured) {
setForm((current) => ({
...current,
@@ -135,6 +139,7 @@ export function ConfigSyncPage() {
return api.onConfigSyncChanged((next) => {
setState(next);
setAllowInsecureHttp(next.allowInsecureHttp === true);
+ setRemoteMode(next.remoteMode ?? "strict");
});
}, [refresh]);
@@ -144,6 +149,13 @@ export function ConfigSyncPage() {
const run = async (
operation: "test" | "configure" | "sync" | "unlock" | "disconnect",
) => {
+ if (
+ operation === "configure" &&
+ remoteMode === "appendOnly" &&
+ !window.confirm(t("settings.configSync.appendOnlyConfirm"))
+ ) {
+ return;
+ }
setBusy(operation);
setError(null);
setNotice(null);
@@ -160,11 +172,16 @@ export function ConfigSyncPage() {
includeSecrets: selection.credentials,
includeMemory: selection.memory,
automaticSync: true,
+ remoteMode,
});
setNotice(
- result.conditionalWrites
- ? t("settings.configSync.testSuccess")
- : t("settings.configSync.testUnsupported"),
+ remoteMode === "appendOnly"
+ ? result.appendOnly
+ ? t("settings.configSync.testAppendOnlySuccess")
+ : t("settings.configSync.testAppendOnlyUnsupported")
+ : result.conditionalWrites
+ ? t("settings.configSync.testSuccess")
+ : t("settings.configSync.testUnsupported"),
);
} else if (operation === "configure") {
await api.configSyncConfigure({
@@ -179,6 +196,7 @@ export function ConfigSyncPage() {
includeSecrets: selection.credentials,
includeMemory: selection.memory,
automaticSync: true,
+ remoteMode,
});
setState(await api.configSyncSyncNow());
setForm((current) => ({ ...current, appPassword: "", backupPassword: "" }));
@@ -192,6 +210,7 @@ export function ConfigSyncPage() {
setState(await api.configSyncDisconnect());
setHistory([]);
setAllowInsecureHttp(false);
+ setRemoteMode("strict");
setForm((current) => ({ ...current, appPassword: "", backupPassword: "" }));
setSelection(DEFAULT_SELECTION);
}
@@ -394,6 +413,33 @@ export function ConfigSyncPage() {
</div>
</div>
) : null}
+ <Field
+ label={t("settings.configSync.remoteMode")}
+ hint={t("settings.configSync.remoteModeHint")}
+ >
+ <SettingsMenuSelect
+ fullWidth
+ label={t("settings.configSync.remoteMode")}
+ value={remoteMode}
+ disabled={busy !== null}
+ options={[
+ {
+ id: "strict",
+ label: t("settings.configSync.remoteModeStrict"),
+ },
+ {
+ id: "appendOnly",
+ label: t("settings.configSync.remoteModeAppendOnly"),
+ },
+ ]}
+ onChange={(value) => setRemoteMode(value as ConfigSyncRemoteMode)}
+ />
+ </Field>
+ {remoteMode === "appendOnly" ? (
+ <div className="settings-config-sync-warning" role="alert">
+ {t("settings.configSync.appendOnlyWarning")}
+ </div>
+ ) : null}
<Field label={t("settings.configSync.username")}>
<Input
value={form.username}
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index 54efa37e5..6f5035a19 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -594,7 +594,12 @@ export const api = {
configSyncConfigure: (input: ConfigSyncConfigureInput) =>
invoke<ConfigSyncState>(IPC.invoke.configSyncConfigure, input),
configSyncTest: (input: Omit<ConfigSyncConfigureInput, "backupPassword"> & { backupPassword?: string }) =>
- invoke<{ ok: boolean; conditionalWrites: boolean; message?: string }>(
+ invoke<{
+ ok: boolean;
+ conditionalWrites: boolean;
+ appendOnly: boolean;
+ message?: string;
+ }>(
IPC.invoke.configSyncTest,
input,
),
diff --git a/apps/desktop/test/config-sync-settings.test.mjs b/apps/desktop/test/config-sync-settings.test.mjs
index 60050e509..749465ab0 100644
--- a/apps/desktop/test/config-sync-settings.test.mjs
+++ b/apps/desktop/test/config-sync-settings.test.mjs
@@ -23,6 +23,10 @@ test("cloud sync keeps credentials and vault operations on the host boundary", (
assert.match(syncPage, /setState\(await api\.configSyncSyncNow\(\)\)/);
assert.match(syncPage, /allowInsecureHttp/);
assert.match(syncPage, /settings\.configSync\.allowInsecureHttpWarning/);
+ assert.match(syncPage, /settings\.configSync\.remoteMode/);
+ assert.match(syncPage, /settings\.configSync\.appendOnlyWarning/);
+ assert.match(syncPage, /settings\.configSync\.appendOnlyConfirm/);
+ assert.match(syncPage, /remoteMode/);
assert.match(syncPage, /api\.configSyncUnlock\(/);
assert.match(syncPage, /api\.configSyncMapProject\(/);
assert.match(syncPage, /api\.configSyncListHistory\(/);
diff --git a/crates/host-core/src/config_sync/coordinator.rs b/crates/host-core/src/config_sync/coordinator.rs
index ef0ffc755..598eced84 100644
--- a/crates/host-core/src/config_sync/coordinator.rs
+++ b/crates/host-core/src/config_sync/coordinator.rs
@@ -81,40 +81,98 @@ pub(super) async fn sync_once(
};
let transport = transport_with_password(&config, transport_password)?;
ensure_remote_collections(&transport, &config).await?;
- let remote_head = read_remote_head(&transport, &config, &key).await?;
- let (remote, remote_resources) = if let Some((head, _)) = remote_head.as_ref() {
- let value = read_remote_revision(&transport, &config, &key, &head.revision_id).await?;
- (Some(value.0), value.1)
- } else {
- (None, BTreeMap::new())
- };
- let merged = merge::three_way(base.as_ref(), &local.manifest, remote.as_ref())?;
- if let (Some((head, _)), Some(remote)) = (remote_head.as_ref(), remote.as_ref()) {
- // Skip publication when the acknowledged base, current local
- // snapshot, and remote head agree for every subscribed domain.
- // A remote-only change in an opted-out category is already
- // represented by the remote head. A fresh device with selected
- // remote content still has to stage it for approval and
- // activation, even though the merge result equals the remote
- // entities.
- let no_selected_change =
- selected_manifests_equal(base.as_ref(), Some(remote), &selection(&config))
- && selected_manifests_equal(
- Some(&local.manifest),
+ let (remote_head, remote, remote_resources, remote_parent_ids, remote_conflicts) =
+ if config.remote_mode == RemoteMode::AppendOnly {
+ let append_only = read_append_only_remote(&transport, &config, &key).await?;
+ if let Some(append_only) = append_only {
+ let remote_merge = merge_append_only_tips(base.as_ref(), &append_only.tips)?;
+ let remote = RevisionManifest {
+ format: REVISION_FORMAT.into(),
+ version: 1,
+ revision_id: append_only
+ .tip_ids
+ .first()
+ .cloned()
+ .unwrap_or_else(|| "remote-merge".into()),
+ parents: append_only.tip_ids.clone(),
+ created_at: Utc::now().to_rfc3339(),
+ entities: remote_merge.entities,
+ resource_ids: append_only.resources.keys().cloned().collect(),
+ };
+ (
+ None,
Some(remote),
- &selection(&config),
- );
- if no_selected_change && remote.entities == merged.entities {
- let mut st = state.lock().await;
- let mut next_config = config.clone();
- next_config.last_success_at = Some(Utc::now().to_rfc3339());
- next_config.last_revision_id = Some(head.revision_id.clone());
- next_config.last_local_digest = Some(local_digest);
- next_config.local_change_seen_at = None;
- clear_error(&mut next_config);
- save_config(&st, &next_config)?;
- send_state_notification(tx, &mut st);
- return Ok(());
+ append_only.resources,
+ append_only.tip_ids,
+ remote_merge.conflicts,
+ )
+ } else {
+ (None, None, BTreeMap::new(), Vec::new(), Vec::new())
+ }
+ } else {
+ let remote_head = read_remote_head(&transport, &config, &key).await?;
+ let (remote, remote_resources) = if let Some((head, _)) = remote_head.as_ref() {
+ let value =
+ read_remote_revision(&transport, &config, &key, &head.revision_id).await?;
+ (Some(value.0), value.1)
+ } else {
+ (None, BTreeMap::new())
+ };
+ let parent_ids = remote_head
+ .as_ref()
+ .map(|(head, _)| vec![head.revision_id.clone()])
+ .unwrap_or_default();
+ (
+ remote_head,
+ remote,
+ remote_resources,
+ parent_ids,
+ Vec::new(),
+ )
+ };
+ let merge::MergeResult {
+ entities: local_entities,
+ conflicts: local_conflicts,
+ } = merge::three_way(base.as_ref(), &local.manifest, remote.as_ref())?;
+ let merged = merge::MergeResult {
+ entities: local_entities,
+ conflicts: remote_conflicts
+ .into_iter()
+ .chain(local_conflicts)
+ .collect(),
+ };
+ let can_skip_publication =
+ config.remote_mode == RemoteMode::Strict || remote_parent_ids.len() <= 1;
+ if can_skip_publication {
+ if let (Some(remote), true) = (remote.as_ref(), !remote_parent_ids.is_empty()) {
+ // Skip publication when the acknowledged base, current local
+ // snapshot, and remote head agree for every subscribed domain.
+ // A remote-only change in an opted-out category is already
+ // represented by the remote head. A fresh device with selected
+ // remote content still has to stage it for approval and
+ // activation, even though the merge result equals the remote
+ // entities.
+ let no_selected_change =
+ selected_manifests_equal(base.as_ref(), Some(remote), &selection(&config))
+ && selected_manifests_equal(
+ Some(&local.manifest),
+ Some(remote),
+ &selection(&config),
+ )
+ && merged.conflicts.is_empty()
+ && remote.entities == merged.entities;
+ if no_selected_change {
+ let mut st = state.lock().await;
+ let mut next_config = config.clone();
+ next_config.last_success_at = Some(Utc::now().to_rfc3339());
+ next_config.last_revision_id = remote_parent_ids.first().cloned();
+ next_config.last_local_digest = Some(local_digest);
+ next_config.local_change_seen_at = None;
+ clear_error(&mut next_config);
+ save_config(&st, &next_config)?;
+ send_state_notification(tx, &mut st);
+ return Ok(());
+ }
}
}
let mut resources = local.resources.clone();
@@ -125,10 +183,7 @@ pub(super) async fn sync_once(
format: REVISION_FORMAT.into(),
version: 1,
revision_id: revision_id.clone(),
- parents: remote_head
- .as_ref()
- .map(|(head, _)| vec![head.revision_id.clone()])
- .unwrap_or_default(),
+ parents: remote_parent_ids.clone(),
created_at: Utc::now().to_rfc3339(),
entities: merged.entities.clone(),
resource_ids: resources.keys().cloned().collect(),
@@ -136,19 +191,31 @@ pub(super) async fn sync_once(
resources,
};
upload_snapshot(&transport, &config, &key, &candidate).await?;
- let head = RemoteHead {
- format: FORMAT.into(),
- version: 1,
- revision_id: candidate.manifest.revision_id.clone(),
+ let published = if config.remote_mode == RemoteMode::AppendOnly {
+ publish_append_only_head(
+ &transport,
+ &config,
+ &key,
+ &config.device_id,
+ &candidate.manifest.revision_id,
+ )
+ .await
+ .map(|_| true)?
+ } else {
+ let head = RemoteHead {
+ format: FORMAT.into(),
+ version: 1,
+ revision_id: candidate.manifest.revision_id.clone(),
+ };
+ publish_head(
+ &transport,
+ &config,
+ &key,
+ &head,
+ remote_head.as_ref().map(|(_, etag)| etag.as_str()),
+ )
+ .await?
};
- let published = publish_head(
- &transport,
- &config,
- &key,
- &head,
- remote_head.as_ref().map(|(_, etag)| etag.as_str()),
- )
- .await?;
if !published {
let jitter_ms = u64::from(Uuid::new_v4().as_bytes()[0] % 31);
tokio::time::sleep(std::time::Duration::from_millis(
@@ -173,6 +240,7 @@ pub(super) async fn sync_once(
store_pending(&st, &key, &journal)?;
}
let mut next_config = config.clone();
+ let candidate_revision_id = candidate.manifest.revision_id.clone();
let apply_bundle_state = PendingBundle {
manifest: candidate.manifest,
local_before: Some(local.manifest.clone()),
@@ -180,7 +248,7 @@ pub(super) async fn sync_once(
approvals: pending.approvals,
conflicts: pending.conflicts,
journal_state: "applying".into(),
- remote_revision_id: head.revision_id,
+ remote_revision_id: candidate_revision_id,
};
apply_bundle(
state,
@@ -191,8 +259,10 @@ pub(super) async fn sync_once(
&apply_bundle_state,
)
.await?;
- if let Err(error) = cleanup_history(state, &transport, &config, &key).await {
- tracing::warn!(error = %error, "config sync history cleanup failed after sync");
+ if config.remote_mode == RemoteMode::Strict {
+ if let Err(error) = cleanup_history(state, &transport, &config, &key).await {
+ tracing::warn!(error = %error, "config sync history cleanup failed after sync");
+ }
}
let mut st = state.lock().await;
send_state_notification(tx, &mut st);
diff --git a/crates/host-core/src/config_sync/engine.rs b/crates/host-core/src/config_sync/engine.rs
index 9525ee4a4..2eadbe2dd 100644
--- a/crates/host-core/src/config_sync/engine.rs
+++ b/crates/host-core/src/config_sync/engine.rs
@@ -43,7 +43,8 @@ pub(crate) use handlers::{
};
use history::cleanup_history;
use remote::{
- ensure_remote_collections, object_path, publish_head, read_remote_head, read_remote_manifest,
+ ensure_remote_collections, merge_append_only_tips, object_path, publish_append_only_head,
+ publish_head, read_append_only_remote, read_remote_head, read_remote_manifest,
read_remote_revision, revision_path, upload_snapshot, validate_remote_id,
};
@@ -59,6 +60,18 @@ const MAX_HISTORY_SCAN: usize = 256;
const MAX_RETAINED_REVISIONS: usize = 30;
const HISTORY_GRACE_SECONDS: i64 = 60 * 60;
+#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub(crate) enum RemoteMode {
+ #[default]
+ Strict,
+ AppendOnly,
+}
+
+fn new_device_id() -> String {
+ Uuid::new_v4().to_string()
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StoredConfig {
@@ -69,6 +82,10 @@ pub struct StoredConfig {
pub directory: String,
pub device_label: String,
pub allow_insecure_http: bool,
+ #[serde(default)]
+ pub remote_mode: RemoteMode,
+ #[serde(default = "new_device_id")]
+ pub device_id: String,
/// Endpoint-specific compatibility for servers that report missing GETs as 502.
#[serde(default)]
pub missing_object_status: Option<u16>,
@@ -211,6 +228,7 @@ struct PublicState {
#[serde(skip_serializing_if = "Option::is_none")]
device_label: Option<String>,
allow_insecure_http: bool,
+ remote_mode: RemoteMode,
categories: BTreeMap<String, bool>,
include_secrets: bool,
include_memory: bool,
@@ -627,6 +645,7 @@ pub fn public_state(st: &mut AppState) -> Result<Value> {
directory: None,
device_label: None,
allow_insecure_http: false,
+ remote_mode: RemoteMode::Strict,
categories: default_categories(),
include_secrets: false,
include_memory: false,
@@ -721,6 +740,7 @@ pub fn public_state(st: &mut AppState) -> Result<Value> {
directory: Some(config_ref.directory.clone()),
device_label: Some(config_ref.device_label.clone()),
allow_insecure_http: config_ref.allow_insecure_http,
+ remote_mode: config_ref.remote_mode,
categories: config_ref.categories.clone(),
include_secrets: config_ref.include_secrets,
include_memory: config_ref.include_memory,
@@ -799,6 +819,13 @@ fn config_from_input(
.and_then(Value::as_bool)
.or_else(|| existing.map(|value| value.include_secrets))
.unwrap_or(false);
+ let remote_mode = input
+ .get("remoteMode")
+ .and_then(Value::as_str)
+ .map(parse_remote_mode)
+ .transpose()?
+ .or_else(|| existing.map(|value| value.remote_mode))
+ .unwrap_or_default();
let mut categories = parse_category_selection(
input.get("categories"),
existing.map(|value| &value.categories),
@@ -817,6 +844,11 @@ fn config_from_input(
.and_then(Value::as_bool)
.or_else(|| existing.map(|value| value.allow_insecure_http))
.unwrap_or(false),
+ remote_mode,
+ device_id: existing
+ .map(|value| value.device_id.clone())
+ .filter(|value| !value.is_empty())
+ .unwrap_or_else(new_device_id),
missing_object_status: existing.and_then(|value| value.missing_object_status),
categories,
include_secrets,
@@ -857,6 +889,14 @@ fn config_from_input(
})
}
+fn parse_remote_mode(value: &str) -> Result<RemoteMode> {
+ match value {
+ "strict" => Ok(RemoteMode::Strict),
+ "appendOnly" => Ok(RemoteMode::AppendOnly),
+ _ => bail!("CONFIG_SYNC_INVALID: unsupported WebDAV sync mode"),
+ }
+}
+
fn mark_error(config: &mut StoredConfig, error: &anyhow::Error) {
let message = error.to_string();
config.last_error_code = if message.starts_with("CONFIG_SYNC_UNSUPPORTED") {
@@ -1091,6 +1131,14 @@ mod tests {
async fn configure_test_device(
data_dir: &Path,
endpoint: &str,
+ ) -> Result<Arc<Mutex<AppState>>> {
+ configure_test_device_mode(data_dir, endpoint, "strict").await
+ }
+
+ async fn configure_test_device_mode(
+ data_dir: &Path,
+ endpoint: &str,
+ remote_mode: &str,
) -> Result<Arc<Mutex<AppState>>> {
let state = Arc::new(Mutex::new(AppState::open(data_dir)?));
configure(
@@ -1103,6 +1151,7 @@ mod tests {
"deviceLabel": "test-device",
"backupPassword": "portable-backup-password",
"allowInsecureHttp": true,
+ "remoteMode": remote_mode,
"categories": {
"application": true,
"providers": true,
@@ -1119,6 +1168,53 @@ mod tests {
Ok(state)
}
+ #[tokio::test]
+ async fn append_only_mode_syncs_with_a_server_that_ignores_preconditions() -> Result<()> {
+ let fixture = crate::config_sync::transport::tests::fixture_ignoring_preconditions().await;
+ let device_a_dir = tempfile::tempdir()?;
+ let device_b_dir = tempfile::tempdir()?;
+ let device_a =
+ configure_test_device_mode(device_a_dir.path(), &fixture.endpoint, "appendOnly")
+ .await?;
+ let device_b =
+ configure_test_device_mode(device_b_dir.path(), &fixture.endpoint, "appendOnly")
+ .await?;
+ let (tx, _rx) = mpsc::unbounded_channel();
+
+ let (a_state, b_state) = tokio::join!(
+ sync_now(device_a.clone(), tx.clone()),
+ sync_now(device_b.clone(), tx.clone())
+ );
+ assert!(
+ a_state.is_ok(),
+ "device A compatibility sync failed: {a_state:?}"
+ );
+ assert!(
+ b_state.is_ok(),
+ "device B compatibility sync failed: {b_state:?}"
+ );
+
+ let state = device_a.lock().await;
+ let config = load_config(&state)?.expect("configured device");
+ let key = local_vault_key(&state, &config)?.expect("unlocked device");
+ let transport = transport_with_password(&config, String::new())?;
+ let remote = read_append_only_remote(&transport, &config, &key)
+ .await?
+ .expect("compatibility revisions");
+ assert!(!remote.tip_ids.is_empty());
+ assert!(remote.tip_ids.len() <= 2);
+ assert!(
+ transport
+ .list_children(&remote::compatibility_heads_path(&config))
+ .await?
+ .len()
+ >= 2
+ );
+
+ fixture.task.abort();
+ Ok(())
+ }
+
#[tokio::test]
async fn two_devices_sync_credentials_capabilities_and_disjoint_edit() -> Result<()> {
let fixture = crate::config_sync::transport::tests::fixture(false).await;
diff --git a/crates/host-core/src/config_sync/engine_history.rs b/crates/host-core/src/config_sync/engine_history.rs
index 4d59f41f7..a128e718d 100644
--- a/crates/host-core/src/config_sync/engine_history.rs
+++ b/crates/host-core/src/config_sync/engine_history.rs
@@ -41,6 +41,13 @@ pub(super) async fn cleanup_history(
config: &StoredConfig,
key: &VaultKey,
) -> Result<()> {
+ if config.remote_mode == RemoteMode::AppendOnly {
+ // There is no cross-device acknowledgement protocol for an
+ // unconditional WebDAV backend. Retaining every immutable revision
+ // keeps a late device head recoverable instead of deleting a branch
+ // that another device has not observed yet.
+ return Ok(());
+ }
let Some((head, _)) = read_remote_head(transport, config, key).await? else {
return Ok(());
};
@@ -122,6 +129,35 @@ pub(super) async fn list_history(state: Arc<Mutex<AppState>>) -> Result<Value> {
(config, key, password)
};
let transport = transport_with_password(&config, transport_password)?;
+ if config.remote_mode == RemoteMode::AppendOnly {
+ let Some(remote) = read_append_only_remote(&transport, &config, &key).await? else {
+ return Ok(json!([]));
+ };
+ let current = remote.tip_ids.iter().cloned().collect::<BTreeSet<_>>();
+ let mut by_id = BTreeMap::new();
+ for tip_id in &remote.tip_ids {
+ for manifest in history_chain(&transport, &config, &key, tip_id).await? {
+ by_id
+ .entry(manifest.revision_id.clone())
+ .or_insert(manifest);
+ }
+ }
+ let mut history = by_id.into_values().collect::<Vec<_>>();
+ history.sort_by(|left, right| right.created_at.cmp(&left.created_at));
+ return Ok(serde_json::to_value(
+ history
+ .into_iter()
+ .map(|manifest| PublicHistoryEntry {
+ current: current.contains(&manifest.revision_id),
+ revision_id: manifest.revision_id,
+ created_at: manifest.created_at,
+ parent_revision_ids: manifest.parents,
+ entity_count: manifest.entities.len(),
+ resource_count: manifest.resource_ids.len(),
+ })
+ .collect::<Vec<_>>(),
+ )?);
+ }
let Some((head, _)) = read_remote_head(&transport, &config, &key).await? else {
return Ok(json!([]));
};
@@ -206,9 +242,6 @@ pub(super) async fn change_password(state: Arc<Mutex<AppState>>, params: Value)
let Some((remote_header_bytes, remote_etag)) = transport.get("header").await? else {
bail!("CONFIG_SYNC_REMOTE: remote vault header is missing");
};
- let remote_etag = remote_etag.ok_or_else(|| {
- anyhow!("CONFIG_SYNC_UNSUPPORTED: remote vault header does not expose a strong ETag")
- })?;
let remote_header: VaultHeader =
serde_json::from_slice(&remote_header_bytes).context("decode remote vault header")?;
if remote_header.vault_id != config.vault_id {
@@ -219,12 +252,33 @@ pub(super) async fn change_password(state: Arc<Mutex<AppState>>, params: Value)
bail!("CONFIG_SYNC_CONFLICT: local and remote vault keys do not match");
}
let next_header = rewrap_vault(&remote_header, &key, new_password)?;
- let published = transport
- .put_if_match("header", &remote_etag, serde_json::to_vec(&next_header)?)
- .await?;
+ let published = if config.remote_mode == RemoteMode::AppendOnly {
+ transport
+ .put_unconditional("header", serde_json::to_vec(&next_header)?)
+ .await?;
+ true
+ } else {
+ let remote_etag = remote_etag.ok_or_else(|| {
+ anyhow!("CONFIG_SYNC_UNSUPPORTED: remote vault header does not expose a strong ETag")
+ })?;
+ transport
+ .put_if_match("header", &remote_etag, serde_json::to_vec(&next_header)?)
+ .await?
+ };
if !published {
bail!("CONFIG_SYNC_CONFLICT: remote vault header changed while changing password");
}
+ let Some((stored_header, _)) = transport.get("header").await? else {
+ bail!("CONFIG_SYNC_REMOTE: remote vault header disappeared after password change");
+ };
+ let stored_header: VaultHeader = serde_json::from_slice(&stored_header)?;
+ if stored_header.vault_id != config.vault_id {
+ bail!("CONFIG_SYNC_CONFLICT: remote vault changed while changing password");
+ }
+ let stored_key = unlock_vault(&stored_header, new_password)?;
+ if stored_key.as_bytes() != key.as_bytes() {
+ bail!("CONFIG_SYNC_CONFLICT: remote vault key changed while changing password");
+ }
config.vault_header = next_header;
let mut st = state.lock().await;
save_config(&st, &config)?;
@@ -272,9 +326,21 @@ pub(super) async fn restore(
(config, key, base, local, password)
};
let transport = transport_with_password(&config, transport_password)?;
- let Some((current_head, current_etag)) = read_remote_head(&transport, &config, &key).await?
- else {
- bail!("CONFIG_SYNC_REMOTE: cannot restore from an empty vault");
+ let (parent_ids, current_etag) = if config.remote_mode == RemoteMode::AppendOnly {
+ let Some(remote) = read_append_only_remote(&transport, &config, &key).await? else {
+ bail!("CONFIG_SYNC_REMOTE: cannot restore from an empty vault");
+ };
+ if remote.tip_ids.is_empty() {
+ bail!("CONFIG_SYNC_REMOTE: cannot restore from an empty vault");
+ }
+ (remote.tip_ids, None)
+ } else {
+ let Some((current_head, current_etag)) =
+ read_remote_head(&transport, &config, &key).await?
+ else {
+ bail!("CONFIG_SYNC_REMOTE: cannot restore from an empty vault");
+ };
+ (vec![current_head.revision_id], Some(current_etag))
};
let (target, target_resources) =
read_remote_revision(&transport, &config, &key, revision_id).await?;
@@ -284,7 +350,7 @@ pub(super) async fn restore(
format: REVISION_FORMAT.into(),
version: 1,
revision_id: candidate_id.clone(),
- parents: vec![current_head.revision_id.clone()],
+ parents: parent_ids,
created_at: Utc::now().to_rfc3339(),
entities: target.entities.clone(),
resource_ids: target_resources.keys().cloned().collect(),
@@ -292,7 +358,10 @@ pub(super) async fn restore(
resources: target_resources,
};
upload_snapshot(&transport, &config, &key, &candidate).await?;
- if !publish_head(
+ if config.remote_mode == RemoteMode::AppendOnly {
+ publish_append_only_head(&transport, &config, &key, &config.device_id, &candidate_id)
+ .await?;
+ } else if !publish_head(
&transport,
&config,
&key,
@@ -301,7 +370,7 @@ pub(super) async fn restore(
version: 1,
revision_id: candidate_id.clone(),
},
- Some(&current_etag),
+ current_etag.as_deref(),
)
.await?
{
@@ -349,8 +418,10 @@ pub(super) async fn restore(
)
.await?;
}
- if let Err(error) = cleanup_history(&state, &transport, &config, &key).await {
- tracing::warn!(error = %error, "config sync history cleanup failed after restore");
+ if config.remote_mode == RemoteMode::Strict {
+ if let Err(error) = cleanup_history(&state, &transport, &config, &key).await {
+ tracing::warn!(error = %error, "config sync history cleanup failed after restore");
+ }
}
let mut st = state.lock().await;
send_state_notification(&tx, &mut st);
diff --git a/crates/host-core/src/config_sync/engine_remote.rs b/crates/host-core/src/config_sync/engine_remote.rs
index 21dd580e0..64aa00e28 100644
--- a/crates/host-core/src/config_sync/engine_remote.rs
+++ b/crates/host-core/src/config_sync/engine_remote.rs
@@ -36,7 +36,7 @@ pub(super) async fn ensure_remote_collections(
transport
.ensure_collection(&format!("vault/{}", config.vault_id))
.await?;
- for child in ["objects", "revisions"] {
+ for child in ["objects", "revisions", "heads"] {
transport
.ensure_collection(&format!("vault/{}/{}", config.vault_id, child))
.await?;
@@ -60,6 +60,16 @@ pub(super) fn head_path(config: &StoredConfig) -> String {
remote_path(config, "head")
}
+pub(super) fn compatibility_heads_path(config: &StoredConfig) -> String {
+ remote_path(config, "heads")
+}
+
+pub(super) fn compatibility_head_path(config: &StoredConfig, device_id: &str) -> Result<String> {
+ validate_remote_id(&config.vault_id, "vault")?;
+ validate_remote_id(device_id, "device")?;
+ Ok(remote_path(config, &format!("heads/{device_id}")))
+}
+
pub(super) fn serialize_json<T: Serialize>(value: &T) -> Result<Vec<u8>> {
Ok(serde_json::to_vec(value)?)
}
@@ -85,6 +95,192 @@ pub(super) async fn read_remote_head(
Ok(Some((head, etag)))
}
+#[derive(Debug)]
+pub(super) struct AppendOnlyRemote {
+ pub tip_ids: Vec<String>,
+ pub tips: Vec<RevisionManifest>,
+ pub resources: BTreeMap<String, Vec<u8>>,
+}
+
+fn is_ancestor(
+ manifests: &BTreeMap<String, RevisionManifest>,
+ ancestor: &str,
+ descendant: &str,
+) -> bool {
+ let mut pending = vec![descendant.to_string()];
+ let mut seen = BTreeSet::new();
+ while let Some(revision_id) = pending.pop() {
+ if !seen.insert(revision_id.clone()) {
+ continue;
+ }
+ if revision_id == ancestor {
+ return true;
+ }
+ if let Some(manifest) = manifests.get(&revision_id) {
+ pending.extend(manifest.parents.iter().cloned());
+ }
+ }
+ false
+}
+
+pub(super) async fn read_append_only_remote(
+ transport: &WebDavTransport,
+ config: &StoredConfig,
+ key: &VaultKey,
+) -> Result<Option<AppendOnlyRemote>> {
+ let mut head_revision_ids = BTreeSet::new();
+ for device_id in transport
+ .list_children(&compatibility_heads_path(config))
+ .await?
+ {
+ validate_remote_id(&device_id, "device")?;
+ let path = compatibility_head_path(config, &device_id)?;
+ let Some((ciphertext, _)) = transport.get(&path).await? else {
+ bail!("CONFIG_SYNC_REMOTE: compatibility head disappeared");
+ };
+ let plain = decrypt_object(
+ key,
+ &format!("append-head/{device_id}"),
+ &config.vault_id,
+ &ciphertext,
+ )?;
+ let head: RemoteHead =
+ serde_json::from_slice(&plain).context("decode compatibility head")?;
+ if head.format != FORMAT || head.version != 1 {
+ bail!("CONFIG_SYNC_UNSUPPORTED: compatibility head format is not supported");
+ }
+ validate_remote_id(&head.revision_id, "revision")?;
+ head_revision_ids.insert(head.revision_id);
+ }
+
+ // A vault created by strict mode may be joined explicitly in append-only
+ // mode. Treat the old shared head as one input while the first
+ // compatibility head is published; strict-mode devices are warned in the
+ // UI and must not remain subscribed to the same vault.
+ if let Some((ciphertext, _)) = transport.get(&head_path(config)).await? {
+ let plain = decrypt_object(key, "head", &config.vault_id, &ciphertext)?;
+ let head: RemoteHead = serde_json::from_slice(&plain).context("decode legacy head")?;
+ if head.format != FORMAT || head.version != 1 {
+ bail!("CONFIG_SYNC_UNSUPPORTED: legacy head format is not supported");
+ }
+ validate_remote_id(&head.revision_id, "revision")?;
+ head_revision_ids.insert(head.revision_id);
+ }
+
+ if head_revision_ids.is_empty() {
+ return Ok(None);
+ }
+
+ let mut manifests = BTreeMap::new();
+ let mut pending = head_revision_ids.iter().cloned().collect::<Vec<_>>();
+ while let Some(revision_id) = pending.pop() {
+ if manifests.contains_key(&revision_id) {
+ continue;
+ }
+ if manifests.len() >= MAX_HISTORY_SCAN {
+ bail!("CONFIG_SYNC_LIMIT_EXCEEDED: compatibility history is too large");
+ }
+ let manifest = read_remote_manifest(transport, config, key, &revision_id).await?;
+ pending.extend(manifest.parents.iter().cloned());
+ manifests.insert(revision_id, manifest);
+ }
+
+ let tip_ids = head_revision_ids
+ .iter()
+ .filter(|candidate| {
+ !head_revision_ids
+ .iter()
+ .any(|other| *candidate != other && is_ancestor(&manifests, candidate, other))
+ })
+ .cloned()
+ .collect::<Vec<_>>();
+
+ let mut tips = Vec::new();
+ let mut resources = BTreeMap::new();
+ for revision_id in &tip_ids {
+ let (manifest, revision_resources) =
+ read_remote_revision(transport, config, key, revision_id).await?;
+ for (object_id, bytes) in revision_resources {
+ if let Some(existing) = resources.get(&object_id) {
+ if existing != &bytes {
+ bail!("CONFIG_SYNC_CRYPTO: compatibility resource id collision");
+ }
+ } else {
+ resources.insert(object_id, bytes);
+ }
+ }
+ tips.push(manifest);
+ }
+ if resources.len() > MAX_RESOURCES {
+ bail!("CONFIG_SYNC_LIMIT_EXCEEDED: compatibility revision references too many resources");
+ }
+ Ok(Some(AppendOnlyRemote {
+ tip_ids,
+ tips,
+ resources,
+ }))
+}
+
+pub(super) fn merge_append_only_tips(
+ base: Option<&RevisionManifest>,
+ tips: &[RevisionManifest],
+) -> Result<merge::MergeResult> {
+ let Some(first) = tips.first() else {
+ return Ok(merge::MergeResult {
+ entities: Vec::new(),
+ conflicts: Vec::new(),
+ });
+ };
+ let mut accumulator = first.clone();
+ let mut conflicts = Vec::new();
+ for tip in tips.iter().skip(1) {
+ let merged = merge::three_way(base, &accumulator, Some(tip))?;
+ accumulator.entities = merged.entities;
+ conflicts.extend(merged.conflicts);
+ }
+ Ok(merge::MergeResult {
+ entities: accumulator.entities,
+ conflicts,
+ })
+}
+
+pub(super) async fn publish_append_only_head(
+ transport: &WebDavTransport,
+ config: &StoredConfig,
+ key: &VaultKey,
+ device_id: &str,
+ revision_id: &str,
+) -> Result<()> {
+ let path = compatibility_head_path(config, device_id)?;
+ validate_remote_id(revision_id, "revision")?;
+ let head = RemoteHead {
+ format: FORMAT.into(),
+ version: 1,
+ revision_id: revision_id.into(),
+ };
+ let encrypted = encrypt_object(
+ key,
+ &format!("append-head/{device_id}"),
+ &config.vault_id,
+ &serialize_json(&head)?,
+ )?;
+ transport.put_unconditional(&path, encrypted).await?;
+ let Some((stored, _)) = transport.get(&path).await? else {
+ bail!("CONFIG_SYNC_REMOTE: compatibility head disappeared after upload");
+ };
+ let plain = decrypt_object(
+ key,
+ &format!("append-head/{device_id}"),
+ &config.vault_id,
+ &stored,
+ )?;
+ let stored: RemoteHead = serde_json::from_slice(&plain)?;
+ if stored.revision_id != revision_id {
+ bail!("CONFIG_SYNC_CONFLICT: compatibility head was changed during publication");
+ }
+ Ok(())
+}
+
pub(super) async fn read_remote_revision(
transport: &WebDavTransport,
config: &StoredConfig,
@@ -224,7 +420,13 @@ pub(super) async fn upload_snapshot(
&config.vault_id,
bytes,
)?;
- transport.put_if_none(&path, encrypted).await?;
+ if config.remote_mode == RemoteMode::AppendOnly {
+ if transport.get(&path).await?.is_none() {
+ transport.put_unconditional(&path, encrypted).await?;
+ }
+ } else {
+ transport.put_if_none(&path, encrypted).await?;
+ }
let Some((existing, _)) = transport.get(&path).await? else {
bail!("CONFIG_SYNC_REMOTE: immutable resource disappeared after upload");
};
@@ -246,7 +448,11 @@ pub(super) async fn upload_snapshot(
&manifest_bytes,
)?;
let path = revision_path(config, &snapshot.manifest.revision_id)?;
- transport.put_if_none(&path, encrypted).await?;
+ if config.remote_mode == RemoteMode::AppendOnly {
+ transport.put_unconditional(&path, encrypted).await?;
+ } else {
+ transport.put_if_none(&path, encrypted).await?;
+ }
let Some((existing, _)) = transport.get(&path).await? else {
bail!("CONFIG_SYNC_REMOTE: immutable revision disappeared after upload");
};
@@ -279,3 +485,69 @@ pub(super) async fn publish_head(
Ok(transport.put_if_none(&head_path(config), encrypted).await?)
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn application_entity(payload: serde_json::Value) -> PortableEntity {
+ let mut entity = PortableEntity {
+ domain: domains::DOMAIN_APPLICATION.to_string(),
+ entity_id: "application".to_string(),
+ label: "Application".to_string(),
+ deleted: false,
+ requires_approval: false,
+ secret_bearing: false,
+ mapping_required: false,
+ digest: String::new(),
+ payload,
+ resource_ids: Vec::new(),
+ };
+ domains::refresh_digest(&mut entity);
+ entity
+ }
+
+ fn manifest(
+ revision_id: &str,
+ parents: Vec<String>,
+ entity: PortableEntity,
+ ) -> RevisionManifest {
+ RevisionManifest {
+ format: REVISION_FORMAT.to_string(),
+ version: 1,
+ revision_id: revision_id.to_string(),
+ parents,
+ created_at: "2026-09-22T00:00:00Z".to_string(),
+ entities: vec![entity],
+ resource_ids: Vec::new(),
+ }
+ }
+
+ #[test]
+ fn append_only_tips_merge_disjoint_application_fields() {
+ let base = manifest(
+ "base",
+ Vec::new(),
+ application_entity(json!({"theme": "light", "language": "en"})),
+ );
+ let theme_tip = manifest(
+ "theme-tip",
+ vec!["base".to_string()],
+ application_entity(json!({"theme": "dark", "language": "en"})),
+ );
+ let language_tip = manifest(
+ "language-tip",
+ vec!["base".to_string()],
+ application_entity(json!({"theme": "light", "language": "zh-CN"})),
+ );
+
+ let merged = merge_append_only_tips(Some(&base), &[theme_tip, language_tip])
+ .expect("append-only tips merge");
+ assert!(merged.conflicts.is_empty());
+ assert_eq!(
+ merged.entities[0].payload,
+ json!({"theme": "dark", "language": "zh-CN"})
+ );
+ }
+}
diff --git a/crates/host-core/src/config_sync/handlers.rs b/crates/host-core/src/config_sync/handlers.rs
index 781124cc3..4ba5abd6c 100644
--- a/crates/host-core/src/config_sync/handlers.rs
+++ b/crates/host-core/src/config_sync/handlers.rs
@@ -57,6 +57,13 @@ pub(crate) async fn test(state: Arc<Mutex<AppState>>, params: Value) -> Result<V
.and_then(Value::as_bool)
.or_else(|| existing.as_ref().map(|value| value.allow_insecure_http))
.unwrap_or(false);
+ let remote_mode = params
+ .get("remoteMode")
+ .and_then(Value::as_str)
+ .map(parse_remote_mode)
+ .transpose()?
+ .or_else(|| existing.as_ref().map(|value| value.remote_mode))
+ .unwrap_or_default();
let stored_password = st.secrets.get(WEBDAV_SECRET_REF)?;
let password = params
.get("appPassword")
@@ -75,6 +82,8 @@ pub(crate) async fn test(state: Arc<Mutex<AppState>>, params: Value) -> Result<V
directory: directory.trim().into(),
device_label: "test".into(),
allow_insecure_http: allow_insecure,
+ remote_mode,
+ device_id: Uuid::new_v4().to_string(),
missing_object_status: None,
categories: default_categories(),
include_secrets: false,
@@ -104,7 +113,11 @@ pub(crate) async fn test(state: Arc<Mutex<AppState>>, params: Value) -> Result<V
};
let transport = transport_with_password(&config, password)?;
let probe = transport.probe().await?;
- Ok(json!({ "ok": true, "conditionalWrites": probe.conditional_writes }))
+ Ok(json!({
+ "ok": true,
+ "conditionalWrites": probe.conditional_writes,
+ "appendOnly": probe.append_only,
+ }))
}
pub(crate) async fn configure(state: Arc<Mutex<AppState>>, params: Value) -> Result<Value> {
@@ -161,8 +174,18 @@ pub(crate) async fn configure(state: Arc<Mutex<AppState>>, params: Value) -> Res
.map(str::to_string);
let transport = transport_with_password(&config, transport_password.clone())?;
let probe = transport.probe().await?;
- if !probe.conditional_writes {
- bail!("CONFIG_SYNC_UNSUPPORTED: WebDAV server did not prove reliable conditional writes");
+ match config.remote_mode {
+ RemoteMode::Strict if !probe.conditional_writes => {
+ bail!(
+ "CONFIG_SYNC_UNSUPPORTED: WebDAV server did not prove reliable conditional writes"
+ );
+ }
+ RemoteMode::AppendOnly if !probe.append_only => {
+ bail!(
+ "CONFIG_SYNC_UNSUPPORTED: WebDAV server did not prove append-only directory listing"
+ );
+ }
+ _ => {}
}
let transport = transport.with_probe_result(&probe);
config.missing_object_status = probe.missing_object_status;
@@ -178,14 +201,37 @@ pub(crate) async fn configure(state: Arc<Mutex<AppState>>, params: Value) -> Res
config.vault_id = remote.vault_id.clone();
config.vault_header = remote;
} else {
- let created = transport
- .put_if_none("header", serde_json::to_vec(&config.vault_header)?)
- .await?;
- if !created {
+ if config.remote_mode == RemoteMode::AppendOnly {
+ if had_existing {
+ bail!(
+ "CONFIG_SYNC_CONFLICT: remote vault header is missing; compatibility mode will not reinitialize an existing vault"
+ );
+ }
+ transport
+ .put_unconditional("header", serde_json::to_vec(&config.vault_header)?)
+ .await?;
+ } else {
+ let created = transport
+ .put_if_none("header", serde_json::to_vec(&config.vault_header)?)
+ .await?;
+ if !created {
+ let Some((bytes, _)) = transport.get("header").await? else {
+ bail!("CONFIG_SYNC_REMOTE: vault header disappeared during initialization");
+ };
+ let remote: VaultHeader = serde_json::from_slice(&bytes)?;
+ key = unlock_vault(&remote, backup_password)?;
+ config.vault_id = remote.vault_id.clone();
+ config.vault_header = remote;
+ }
+ }
+ if config.remote_mode == RemoteMode::AppendOnly {
let Some((bytes, _)) = transport.get("header").await? else {
bail!("CONFIG_SYNC_REMOTE: vault header disappeared during initialization");
};
let remote: VaultHeader = serde_json::from_slice(&bytes)?;
+ if had_existing && config.vault_id != remote.vault_id {
+ bail!("CONFIG_SYNC_CONFLICT: selected WebDAV directory belongs to another vault");
+ }
key = unlock_vault(&remote, backup_password)?;
config.vault_id = remote.vault_id.clone();
config.vault_header = remote;
diff --git a/crates/host-core/src/config_sync/transport.rs b/crates/host-core/src/config_sync/transport.rs
index 48a7a5fe0..0f8768ce4 100644
--- a/crates/host-core/src/config_sync/transport.rs
+++ b/crates/host-core/src/config_sync/transport.rs
@@ -5,6 +5,7 @@ use std::net::IpAddr;
use uuid::Uuid;
const MAX_REMOTE_OBJECT_BYTES: usize = 64 * 1024 * 1024;
+const MAX_REMOTE_LIST_ENTRIES: usize = 4096;
#[derive(Debug, Clone)]
pub struct WebDavConfig {
@@ -19,6 +20,7 @@ pub struct WebDavConfig {
#[derive(Debug, Clone)]
pub struct ProbeResult {
pub conditional_writes: bool,
+ pub append_only: bool,
pub missing_object_status: Option<u16>,
}
@@ -238,6 +240,96 @@ impl WebDavTransport {
Ok(Some((Self::limited_bytes(response).await?, etag)))
}
+ pub async fn put_unconditional(&self, relative: &str, body: Vec<u8>) -> Result<()> {
+ let response = self
+ .send(Method::PUT, relative, Some(body), HeaderMap::new())
+ .await?;
+ if !response.status().is_success() {
+ bail!(
+ "CONFIG_SYNC_REMOTE: WebDAV unconditional write returned {}",
+ response.status()
+ );
+ }
+ Ok(())
+ }
+
+ /// List direct children of a WebDAV collection. Append-only compatibility
+ /// mode uses this to discover per-device heads without overwriting a
+ /// shared mutable head. The returned names are intentionally opaque; the
+ /// caller validates them against its domain-specific identifier rules.
+ pub async fn list_children(&self, relative: &str) -> Result<Vec<String>> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ reqwest::header::HeaderName::from_static("depth"),
+ HeaderValue::from_static("1"),
+ );
+ headers.insert(
+ reqwest::header::CONTENT_TYPE,
+ HeaderValue::from_static("application/xml; charset=utf-8"),
+ );
+ let body = br#"<?xml version="1.0" encoding="utf-8"?>
+<D:propfind xmlns:D="DAV:"><D:prop><D:resourcetype/></D:prop></D:propfind>"#
+ .to_vec();
+ let response = self
+ .send(
+ Method::from_bytes(b"PROPFIND").expect("PROPFIND is a valid method"),
+ relative,
+ Some(body),
+ headers,
+ )
+ .await?;
+ if response.status().as_u16() == 405 || response.status().as_u16() == 501 {
+ bail!("CONFIG_SYNC_UNSUPPORTED: WebDAV directory listing is not supported");
+ }
+ if response.status().as_u16() != 207 && !response.status().is_success() {
+ bail!(
+ "CONFIG_SYNC_REMOTE: WebDAV directory listing returned {}",
+ response.status()
+ );
+ }
+ let body = Self::limited_bytes(response).await?;
+ let text = String::from_utf8(body).context("decode WebDAV directory listing")?;
+ let collection_url = self.url(relative)?;
+ let collection_path = collection_url.path().trim_end_matches('/').to_string();
+ let collection_origin = (
+ collection_url.scheme().to_string(),
+ collection_url.host_str().map(str::to_string),
+ collection_url.port_or_known_default(),
+ );
+ let hrefs = regex::Regex::new(
+ r"(?is)<(?:[A-Za-z_][A-Za-z0-9_.-]*:)?href[^>]*>(.*?)</(?:[A-Za-z_][A-Za-z0-9_.-]*:)?href\s*>",
+ )
+ .expect("static WebDAV href expression")
+ .captures_iter(&text)
+ .filter_map(|capture| capture.get(1).map(|value| value.as_str().trim()))
+ .map(xml_unescape)
+ .filter_map(|href| {
+ let href = href
+ .split(['?', '#'])
+ .next()
+ .unwrap_or(&href);
+ let href_url = self.base.join(href).ok()?;
+ let href_origin = (
+ href_url.scheme().to_string(),
+ href_url.host_str().map(str::to_string),
+ href_url.port_or_known_default(),
+ );
+ if href_origin != collection_origin {
+ return None;
+ }
+ let child_path = href_url.path().trim_end_matches('/');
+ let prefix = format!("{collection_path}/");
+ let name = child_path.strip_prefix(&prefix)?;
+ (!name.is_empty() && !name.contains('/')).then(|| name.to_string())
+ })
+ .take(MAX_REMOTE_LIST_ENTRIES + 1)
+ .collect::<Vec<_>>();
+ if hrefs.len() > MAX_REMOTE_LIST_ENTRIES {
+ bail!("CONFIG_SYNC_LIMIT_EXCEEDED: WebDAV directory has too many entries");
+ }
+ Ok(hrefs)
+ }
+
pub async fn put_if_none(&self, relative: &str, body: Vec<u8>) -> Result<bool> {
let mut headers = HeaderMap::new();
headers.insert(IF_NONE_MATCH, HeaderValue::from_static("*"));
@@ -321,6 +413,12 @@ impl WebDavTransport {
.get(&probe)
.await?
.is_some_and(|(bytes, _)| bytes == second_body);
+ let probe_name = probe.rsplit('/').next().unwrap_or_default();
+ let append_only = match self.list_children(".probe").await {
+ Ok(children) => children.iter().any(|child| child == probe_name),
+ Err(error) if error.to_string().starts_with("CONFIG_SYNC_UNSUPPORTED") => false,
+ Err(error) => return Err(error),
+ };
self.delete(&probe).await?;
let missing_object_status = match self
.send(Method::GET, &probe, None, HeaderMap::new())
@@ -336,11 +434,21 @@ impl WebDavTransport {
&& matched_update
&& stale_rejected
&& updated_readable,
+ append_only,
missing_object_status,
})
}
}
+fn xml_unescape(value: &str) -> String {
+ value
+ .replace("&lt;", "<")
+ .replace("&gt;", ">")
+ .replace("&quot;", "\"")
+ .replace("&apos;", "'")
+ .replace("&amp;", "&")
+}
+
fn strong_etag(headers: &HeaderMap) -> Option<String> {
let value = headers.get(ETAG)?.to_str().ok()?.trim();
if value.is_empty() || value.starts_with("W/") {
@@ -364,7 +472,7 @@ pub fn remote_error_is_offline(error: &anyhow::Error) -> bool {
#[cfg(test)]
pub(crate) mod tests {
use super::*;
- use std::collections::{HashMap, HashSet};
+ use std::collections::{BTreeSet, HashMap, HashSet};
use std::sync::{Arc, Mutex};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
@@ -444,6 +552,7 @@ pub(crate) mod tests {
200 => "OK",
201 => "Created",
204 => "No Content",
+ 207 => "Multi-Status",
404 => "Not Found",
405 => "Method Not Allowed",
412 => "Precondition Failed",
@@ -492,6 +601,39 @@ pub(crate) mod tests {
(404, Vec::new(), None)
}
}
+ "PROPFIND" => {
+ let collection = path.trim_end_matches('/');
+ if !state.collections.contains(collection) {
+ (404, Vec::new(), None)
+ } else {
+ let prefix = format!("{collection}/");
+ let mut entries = BTreeSet::new();
+ entries.insert(format!("{collection}/"));
+ for candidate in state
+ .collections
+ .iter()
+ .map(String::as_str)
+ .chain(state.objects.keys().map(String::as_str))
+ {
+ let Some(child) = candidate.strip_prefix(&prefix) else {
+ continue;
+ };
+ if !child.is_empty() && !child.contains('/') {
+ entries.insert(candidate.to_string());
+ }
+ }
+ let mut xml = String::from(
+ r#"<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:">"#,
+ );
+ for entry in entries {
+ xml.push_str(&format!(
+ "<D:response><D:href>{entry}</D:href></D:response>"
+ ));
+ }
+ xml.push_str("</D:multistatus>");
+ (207, xml.into_bytes(), None)
+ }
+ }
"PUT" => {
let existing = state.objects.contains_key(&path);
let none_match = headers
@@ -541,6 +683,10 @@ pub(crate) mod tests {
fixture_with_options(weak_etag, None, false).await
}
+ pub(crate) async fn fixture_ignoring_preconditions() -> Fixture {
+ fixture_with_options(false, None, true).await
+ }
+
async fn fixture_with_options(
weak_etag: bool,
missing_status: Option<u16>,
@@ -619,7 +765,9 @@ pub(crate) mod tests {
async fn local_fixture_proves_conditional_writes() {
let fixture = fixture(false).await;
let transport = fixture_transport(&fixture.endpoint);
- assert!(transport.probe().await.expect("probe").conditional_writes);
+ let probe = transport.probe().await.expect("probe");
+ assert!(probe.conditional_writes);
+ assert!(probe.append_only);
fixture.task.abort();
}
@@ -629,6 +777,26 @@ pub(crate) mod tests {
let transport = fixture_transport(&fixture.endpoint);
let probe = transport.probe().await.expect("probe");
assert!(!probe.conditional_writes);
+ assert!(probe.append_only);
+ fixture.task.abort();
+ }
+
+ #[tokio::test]
+ async fn directory_listing_excludes_the_collection_itself() {
+ let fixture = fixture(false).await;
+ let transport = fixture_transport(&fixture.endpoint);
+ transport
+ .ensure_collection("heads")
+ .await
+ .expect("collection");
+ transport
+ .put_unconditional("heads/device-a", b"head".to_vec())
+ .await
+ .expect("head");
+ assert_eq!(
+ transport.list_children("heads").await.expect("listing"),
+ vec!["device-a".to_string()]
+ );
fixture.task.abort();
}
diff --git a/docs/adr/0300-host-owned-encrypted-portable-configuration-sync.md b/docs/adr/0300-host-owned-encrypted-portable-configuration-sync.md
index 5dfb2a2fa..aed948493 100644
--- a/docs/adr/0300-host-owned-encrypted-portable-configuration-sync.md
+++ b/docs/adr/0300-host-owned-encrypted-portable-configuration-sync.md
@@ -34,19 +34,21 @@ project identities are assigned and retained by Host metadata; project-group
roots use the portable group identity plus ordered root position, so absolute
folder paths never become cross-device identity.
-WebDAV initialization and head publication require reliable conditional writes:
-`If-None-Match: *` for creation and strong-ETag `If-Match` for updates. A CAS
-failure restarts reconciliation. Servers that cannot prove this capability are
-reported as unsupported rather than silently using last-writer-wins. HTTPS is
-the default transport; the settings UI may explicitly acknowledge LAN HTTP
-risk, and Host restricts that exception to localhost, `.local`, or private /
+Strict WebDAV initialization and head publication require reliable conditional
+writes: `If-None-Match: *` for creation and strong-ETag `If-Match` for updates.
+A CAS failure restarts reconciliation. ADR 0301 defines the separately
+confirmed append-only compatibility mode for servers that fail this probe;
+there is no silent downgrade to unconditional last-writer-wins. HTTPS is the
+default transport; the settings UI may explicitly acknowledge LAN HTTP risk,
+and Host restricts that exception to localhost, `.local`, or private /
link-local IP addresses. Public HTTP endpoints remain rejected.
The capability probe may record an endpoint-specific `502 Bad Gateway` response
for a missing object, because some WebDAV gateways use that status instead of
`404`. Only that observed status is treated as absence for subsequent reads;
arbitrary `502` responses are not globally treated as an empty remote. This
-compatibility does not allow servers that ignore conditional-write headers.
+compatibility does not change strict mode; servers that ignore conditional-write
+headers are supported only through the explicit append-only mode in ADR 0301.
## Consequences
@@ -72,9 +74,10 @@ Costs and limits:
WebDAV conditional-write fixture are part of the Host-owned baseline. A
restore creates a new revision and a local recovery point; it does not make
an old copied vault key revocable.
-- Strong conditional-write behavior is stricter than many simple WebDAV
- servers; backup-only behavior must be labeled and must not pretend to be
- bidirectional sync.
+- Strict conditional-write behavior is stricter than many simple WebDAV
+ servers. The explicit append-only mode is a labeled bidirectional
+ compatibility path with retained history and weaker publication guarantees;
+ it must not be presented as strict CAS.
## Alternatives rejected
diff --git a/docs/adr/0301-explicit-append-only-webdav-compatibility-mode.md b/docs/adr/0301-explicit-append-only-webdav-compatibility-mode.md
new file mode 100644
index 000000000..8a15e8ff2
--- /dev/null
+++ b/docs/adr/0301-explicit-append-only-webdav-compatibility-mode.md
@@ -0,0 +1,70 @@
+# ADR 0301: Explicit append-only WebDAV compatibility mode
+
+- Status: Accepted for implementation
+- Date: 2026-09-22
+- Amends: ADR 0300
+
+## Context
+
+Some WebDAV servers accept `If-None-Match` and `If-Match` headers but ignore
+their preconditions. Treating a successful unconditional `PUT` as a compare-
+and-swap would allow two devices to overwrite a shared head without detecting
+the race. CloudDrive-style WebDAV endpoints are useful for local-network sync,
+but a server's WebDAV support does not by itself prove conditional-write
+semantics.
+
+## Decision
+
+Keep strict conditional-write mode as the default. Add an explicitly selected
+append-only compatibility mode for servers that fail the conditional-write
+probe but prove that they can list a WebDAV collection with `PROPFIND`.
+
+Compatibility mode uses the same encrypted header, immutable revision manifests,
+and authenticated resources as strict mode, but changes publication as follows:
+
+1. Each device receives a random stable device identifier.
+2. Each device publishes only its own encrypted pointer at
+ `vault/<vault-id>/heads/<device-id>`; the pointer is verified by a readback.
+3. A sync lists all device pointers, includes a legacy strict head when present,
+ walks their bounded parent graph, removes ancestor pointers, and merges all
+ remaining tips against the last acknowledged base.
+4. New revisions and resources use unique immutable identifiers. Existing
+ resources are read and authenticated before reuse; compatibility mode does
+ not overwrite an existing immutable object.
+5. Compatibility mode retains immutable remote history and does not run remote
+ cleanup, because a server without conditional writes cannot provide a safe
+ cross-device acknowledgement protocol.
+
+The settings page labels the mode as compatibility mode, explains that it does
+not provide atomic compare-and-swap, and requires confirmation before saving.
+All devices sharing a vault must select the same mode. The mode is not a silent
+downgrade, and a server that cannot prove directory listing remains unsupported
+for bidirectional synchronization.
+
+## Consequences
+
+- Concurrent writers publish separate tips instead of silently overwriting one
+ shared head; compatible disjoint edits can still converge through the normal
+ merge engine.
+- A device with a duplicated device identifier or a server that changes a
+ device pointer during readback is reported as a conflict rather than treated
+ as converged.
+- Compatibility mode is not equivalent to strict CAS. A server can still lose
+ an in-flight unconditional write, deny or roll back availability, race vault
+ header initialization, or return an incomplete directory listing. The UI
+ discloses these limits and history is retained to make recovery possible.
+- New-device executable imports remain staged behind the existing digest-bound
+ approval boundary; selecting compatibility mode does not grant activation.
+- Password rewrap updates the encrypted header unconditionally in this mode and
+ verifies the resulting header. Rotation of a copied vault key still requires
+ vault re-encryption and server-credential rotation.
+
+## Alternatives rejected
+
+1. Silently accepting ignored preconditions: unsafe last-writer-wins behavior
+ and data loss under concurrent sync.
+2. Keeping one shared mutable head with an unconditional `PUT`: the exact race
+ this mode is intended to avoid.
+3. Treating every WebDAV `GET` failure as an empty collection: hides outages and
+ can cause accidental reinitialization. Only the endpoint-specific observed
+ missing-object status remains compatible.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index fa77d818c..9d1c8a5c4 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -329,6 +329,7 @@ Each ADR includes:
| 0298 | [The app ships no fonts](0298-remove-bundled-fonts.md) | Accepted (D598; amends ADR 0083 / D232) |
| 0299 | [Subagent context budget and delegate compaction](0299-subagent-context-budget.md) | Accepted for implementation (amends ADR 0064; extends ADR 0062 / ADR 0279) |
| 0300 | [Host-owned encrypted portable configuration sync](0300-host-owned-encrypted-portable-configuration-sync.md) | Accepted for implementation |
+| 0301 | [Explicit append-only WebDAV compatibility mode](0301-explicit-append-only-webdav-compatibility-mode.md) | Accepted for implementation |
| turn-process-and-thinking-display | [Turn process and thinking presentation](turn-process-and-thinking-display.md) | Accepted |
| provider-display-order | [Provider display order](provider-display-order.md) | Accepted |
| registry-header-variable-spelling | [Remote header variables accept the registry's `{name}` spelling](registry-header-variable-spelling.md) | Proposed |
diff --git a/docs/spec/03-runtime/22-config-sync.md b/docs/spec/03-runtime/22-config-sync.md
index b25eb8408..8f85a12ae 100644
--- a/docs/spec/03-runtime/22-config-sync.md
+++ b/docs/spec/03-runtime/22-config-sync.md
@@ -69,8 +69,8 @@ fresh nonce. Resource object IDs are keyed content identifiers, so plaintext
global hashes are not required. The vault envelope version is independent from
the SQLite schema and is bumped when cryptographic derivation changes.
-The remote layout is an opaque header plus immutable revision/resource objects
-and one mutable encrypted head:
+The remote layout is an opaque header plus immutable revision/resource objects.
+Strict mode also has one mutable encrypted head:
```text
<selected-directory>/header
@@ -79,19 +79,40 @@ and one mutable encrypted head:
<selected-directory>/vault/<opaque-vault-id>/objects/<object-id>
```
-Initialization uses `If-None-Match: *`. Existing heads require a strong ETag
-and are published with `If-Match`. A failed precondition restarts
+Strict initialization uses `If-None-Match: *`. Existing heads require a strong
+ETag and are published with `If-Match`. A failed precondition restarts
reconciliation from the newly read head; it never overwrites blindly. The
capability probe writes a temporary object with conditional creation twice,
obtains a strong ETag, verifies a matching `If-Match` update, and verifies a
stale `If-Match` is rejected before the object is removed.
+The settings page also offers an explicit append-only compatibility mode for a
+server that ignores conditional headers. The probe must still prove bounded
+`PROPFIND` directory listing. Compatibility mode adds an opaque per-device
+pointer collection:
+
+```text
+<selected-directory>/vault/<opaque-vault-id>/heads/<device-id>
+```
+
+Each device overwrites only its own encrypted pointer and verifies it by
+reading it back. A sync lists all pointers, includes a legacy strict head when
+present, walks the bounded parent graph, removes ancestor pointers, and merges
+the remaining tips against the acknowledged base. New revisions and resources
+are unique immutable objects; an existing resource is read and authenticated
+before reuse. Compatibility mode retains immutable history and does not run
+remote cleanup because the server cannot provide a safe cross-device
+acknowledgement protocol. All devices sharing a vault must use the same mode.
+This mode is never selected silently and does not claim strict CAS guarantees.
+
Some WebDAV gateways report a missing object as `502 Bad Gateway` instead of
`404 Not Found`. The capability probe records this behavior for the selected
endpoint after deleting its temporary object; subsequent reads treat only that
observed status as absence. Other non-success responses remain errors. This
-does not relax conditional-write requirements: a server that ignores
-`If-None-Match` or `If-Match` remains unsupported for bidirectional sync.
+does not relax strict-mode conditional-write requirements: a server that
+ignores `If-None-Match` or `If-Match` is usable for bidirectional sync only
+after the user selects append-only compatibility mode and the directory-listing
+probe succeeds.
HTTPS is required by default. The settings page may expose an explicit
LAN-risk acknowledgement for HTTP, but Host accepts that exception only for
@@ -104,8 +125,10 @@ parameters are rejected.
## 4. Merge and activation
The local encrypted base is the last acknowledged common revision. Capture,
-remote read, three-way merge, immutable object upload, CAS head publication,
-and local application are serialized per vault. Scalar settings merge by
+remote read, three-way merge, immutable object upload, head publication, and
+local application are serialized per vault. Strict mode uses CAS head
+publication; compatibility mode publishes a per-device pointer and merges
+discovered tips. Scalar settings merge by
declared entity unit; provider records, MCP records, skill packages, and
automation definitions are not merged as arbitrary JSON arrays. Tombstones
represent explicit deletion; an unselected category is not deletion.
@@ -133,9 +156,13 @@ unchanged.
## 5. Settings workflow
Settings → Cloud sync provides WebDAV endpoint credentials, vault password,
-device label, category selection, a capability test, sync-now, unlock, pause,
-folder mapping, approval/rejection, revision history/restore, vault-password
-rewrap, and disconnect controls. The renderer displays
+device label, server compatibility mode, category selection, a capability test,
+sync-now, unlock, pause, folder mapping, approval/rejection, revision
+history/restore, vault-password rewrap, and disconnect controls. Strict CAS is
+the default. Selecting append-only compatibility mode shows a persistent risk
+warning and requires confirmation before configuration is saved; its test
+success reports directory-listing support rather than conditional-write
+support. The renderer displays
`notConfigured`, `locked`, `upToDate`, `localChangesPending`, `syncing`,
`offline`, `unsupportedServer`, `conflict`, `awaitingActivation`, `paused`,
and `error` as distinct states. Disconnect keeps local data and does not delete
@@ -162,12 +189,15 @@ unauthenticated local bundle is an error, not an empty state. Backup format
versioning is independent from the SQLite schema; a newer format is rejected
without truncating the local representation.
-Remote history retains the newest 30 reachable logical revisions and protects
-the current head, merge base, pending conflict references, and recovery points;
-unreferenced objects are deleted only after a grace period and successful
-publication. Restore publishes a new revision after a pre-restore encrypted
-local recovery point is written. A vault-password change CAS-updates the
-wrapped-key header without changing the vault data key; copied old keys are not
+Strict remote history retains the newest 30 reachable logical revisions and
+protects the current head, merge base, pending conflict references, and
+recovery points; unreferenced objects are deleted only after a grace period and
+successful publication. Compatibility mode retains immutable history because
+there is no safe cross-device cleanup acknowledgement. Restore publishes a new
+revision after a pre-restore encrypted local recovery point is written. A
+vault-password change CAS-updates the wrapped-key header in strict mode; in
+compatibility mode it uses an unconditional write followed by authenticated
+readback. Neither mode changes the vault data key; copied old keys are not
cryptographically revoked, so device removal is not treated as revocation.
Project-group mappings accept ordered multi-root bindings and preserve the
diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.md
index d829b61b3..279e15835 100644
--- a/docs/spec/04-ux/06-settings-ia.md
+++ b/docs/spec/04-ux/06-settings-ia.md
@@ -147,8 +147,14 @@ Settings is a **full-window page** that replaces the app sidebar + main chrome (
### Cloud sync
- **Connection**: WebDAV URL, username, app password, remote directory, device
- label, and a separate backup/vault password. The test action uses only a
- temporary remote object and must prove conditional creation and readback.
+ label, a separate backup/vault password, and a server compatibility mode.
+ Strict CAS is the default. The test action uses only temporary remote
+ objects; strict mode must prove conditional creation and readback, while
+ append-only compatibility mode must prove bounded directory listing. Choosing
+ compatibility mode shows a persistent warning and requires confirmation
+ before save. The warning explains that all devices in the vault must use the
+ same mode, history is retained, and concurrent changes may still require
+ review.
- **Portable configuration**: supported categories are selected by default;
credentials and project memory are explicit opt-ins. The preview reports
supported, excluded, secret-bearing, mapping-required, and pending-approval
diff --git a/docs/spec/05-security/01-security.md b/docs/spec/05-security/01-security.md
index f2bc0f847..31ef9f5e3 100644
--- a/docs/spec/05-security/01-security.md
+++ b/docs/spec/05-security/01-security.md
@@ -141,7 +141,10 @@ cannot access the endpoint, WebDAV password, backup password, vault key, or
portable secret values. Host-core validates the selected HTTPS endpoint,
rejects userinfo and redirects, constrains relative paths, bounds remote object
size and KDF parameters, and requires strong conditional-write behavior before
-publishing a head.
+publishing a shared head in strict mode. An explicitly confirmed append-only
+compatibility mode may be used after a bounded `PROPFIND` directory-listing
+probe succeeds; it publishes per-device encrypted pointers and retains
+immutable history rather than pretending an unconditional `PUT` is CAS.
Every remote payload is authenticated ciphertext. The WebDAV server receives
neither the vault password nor the local machine encryption key. Credentials
@@ -154,9 +157,12 @@ Imported commands, endpoints, scripts, skills, plugins, and automations are
staged behind a digest-bound local approval. Local paths and approvals are
overlays, not shared entities. A new device therefore cannot execute a
synchronized capability merely because its desired enabled flag was imported.
-The server can still deny availability or replay a valid old head to a fresh
-device that has no trusted history; sync does not claim availability or
-freshness against a malicious server.
+The compatibility-mode warning states that all devices sharing a vault must
+use the same mode and that concurrent changes can still require review. It
+does not weaken approval, secret export, redirect, path, object-size, or
+freshness protections. The server can still deny availability or replay a
+valid old head to a fresh device that has no trusted history; sync does not
+claim availability or freshness against a malicious server.
## 5. Command execution
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 0f93784d3..6c6930488 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -8006,8 +8006,9 @@ identify the platform validation still needed.
### E2E-CONFIG-SYNC-webdav-portable-configuration
- **Preconditions:** A built task candidate, isolated host profile, and a local
- WebDAV fixture that supports strong ETags and conditional PUT. No real
- WebDAV account, provider, or production desktop.
+ WebDAV fixture that supports strong ETags and conditional PUT, plus a fixture
+ variant that ignores conditional headers but supports `PROPFIND` directory
+ listing. No real WebDAV account, provider, or production desktop.
- **Steps:** 1) Open Settings → Cloud sync and enter the fixture URL, device
label, directory, and backup password. 2) Run the capability test and
confirm it uses temporary objects. 3) Select provider/MCP/skill categories
@@ -8019,23 +8020,30 @@ identify the platform validation still needed.
reject one staged entity, edit disjoint settings on both devices, and sync
again. 7) Exercise a concurrent head writer, wrong password, weak ETag,
ciphertext corruption, redirect, archive traversal, and network interruption.
- 8) Use the explicit LAN HTTP acknowledgement with a loopback/private fixture,
+ 8) On the ignored-precondition fixture, select explicit compatibility mode,
+ confirm the warning, and configure two devices. Verify each device publishes
+ its own encrypted head under the heads collection, a concurrent update is
+ merged from both tips, and compatibility mode does not delete immutable
+ history. Cancel the confirmation once and verify configuration is not saved.
+ 9) Use the explicit LAN HTTP acknowledgement with a loopback/private fixture,
verify the setting survives a state refresh, and confirm a public HTTP
endpoint is rejected even when the checkbox is selected.
-- **Expected:** The test refuses unreliable conditional writes. HTTP remains
- opt-in and is accepted only for localhost, `.local`, or private/link-local
- addresses; public HTTP endpoints are rejected and the UI explains the
- credential exposure risk. A fixture that reports a missing object as 502 is
- accepted only after the capability probe observes that endpoint-specific
- behavior; a server that ignores conditional headers remains unsupported.
- WebDAV sees
+- **Expected:** Strict mode refuses unreliable conditional writes. The explicit
+ compatibility mode accepts only a server that proves bounded directory
+ listing, explains that it is not atomic CAS, and retains per-device tips for
+ merge/recovery. A server that ignores conditional headers is never accepted
+ without that user selection. HTTP remains opt-in and is accepted only for
+ localhost, `.local`, or private/link-local addresses; public HTTP endpoints
+ are rejected and the UI explains the credential exposure risk. A fixture that
+ reports a missing object as 502 is accepted only after the capability probe
+ observes that endpoint-specific behavior. WebDAV sees
only authenticated ciphertext and opaque object names; raw secrets never
appear in renderer state or logs. Identical and disjoint edits converge,
conflicts remain reviewable, explicit deletions use tombstones, category
opt-out is not deletion, and executable imports remain inactive until local
approval and mapping. Recovery never exposes a partial local apply.
- **Specs:** `03-runtime/22-config-sync.md`, `03-runtime/14-secrets-storage.md`,
- `05-security/01-security.md`, ADR 0300.
+ `05-security/01-security.md`, ADR 0300, ADR 0301.
- **Acceptance:** F (persistence), Security, Quality.
- **Milestone:** M6+.
- **Status:** Draft; merge/crypto and in-process WebDAV conditional-write
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index e5378ce78..15373d754 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -682,6 +682,15 @@ sklm: {
allowInsecureHttp: "HTTP für eine vertrauenswürdige LAN-Adresse zulassen",
allowInsecureHttpWarning:
"HTTP verschlüsselt WebDAV-Anmeldedaten nicht. Nur für eine vertrauenswürdige LAN-Adresse aktivieren; öffentliche HTTP-Endpunkte werden abgelehnt.",
+ remoteMode: "Server-Kompatibilität",
+ remoteModeHint:
+ "Der strikte Modus erfordert zuverlässige bedingte Schreibvorgänge. Verwende den Kompatibilitätsmodus nur für Server, die If-Match/If-None-Match ignorieren.",
+ remoteModeStrict: "Striktes CAS (empfohlen)",
+ remoteModeAppendOnly: "Kompatibilitätsmodus (nur anhängen)",
+ appendOnlyWarning:
+ "Dieser Modus ist für WebDAV-Server gedacht, die bedingte Schreibvorgänge ignorieren. Initialisiere den Tresor zuerst auf einem Gerät, bevor weitere Geräte beitreten. Er verwendet gerätespezifische Anhängeköpfe und behält den Remote-Verlauf; alle Geräte in diesem Tresor müssen den Kompatibilitätsmodus verwenden. Gleichzeitige Änderungen müssen möglicherweise geprüft werden.",
+ appendOnlyConfirm:
+ "Dieser Server kann bedingte Schreibvorgänge nicht erzwingen. Der Kompatibilitätsmodus behält den Verlauf, bietet aber kein atomares Compare-and-Swap. Fortfahren?",
username: "Username",
appPassword: "App password",
directory: "Remote directory",
@@ -703,6 +712,10 @@ sklm: {
testSuccess: "The server supports the required conditional writes.",
testUnsupported:
"The server did not prove reliable conditional writes; sync is not enabled.",
+ testAppendOnlySuccess:
+ "The server supports directory listing for append-only compatibility mode.",
+ testAppendOnlyUnsupported:
+ "The server did not prove directory listing for compatibility mode; sync is not enabled.",
enable: "Enable sync",
save: "Save and sync",
configured: "Cloud sync configuration saved.",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index a54e9c7d1..2abd7f319 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -928,6 +928,15 @@ sklm: {
allowInsecureHttp: "Allow HTTP for a trusted LAN address",
allowInsecureHttpWarning:
"HTTP does not encrypt WebDAV credentials. Enable only for a trusted LAN address; public HTTP endpoints are rejected.",
+ remoteMode: "Server compatibility",
+ remoteModeHint:
+ "Strict mode requires reliable conditional writes. Use compatibility mode only for a server that ignores If-Match/If-None-Match.",
+ remoteModeStrict: "Strict CAS (recommended)",
+ remoteModeAppendOnly: "Compatibility mode (append-only)",
+ appendOnlyWarning:
+ "This mode is for WebDAV servers that ignore conditional writes. Initialize the vault on one device before joining from others. It uses per-device append-only heads and retains remote history; every device sharing this vault must use compatibility mode. Concurrent changes may still require review.",
+ appendOnlyConfirm:
+ "This server mode cannot enforce conditional writes. Compatibility mode retains history but cannot provide atomic compare-and-swap. Continue?",
username: "Username",
appPassword: "App password",
directory: "Remote directory",
@@ -950,6 +959,10 @@ sklm: {
testSuccess: "The server supports the required conditional writes.",
testUnsupported:
"The server did not prove reliable conditional writes; sync is not enabled.",
+ testAppendOnlySuccess:
+ "The server supports directory listing for append-only compatibility mode.",
+ testAppendOnlyUnsupported:
+ "The server did not prove directory listing for compatibility mode; sync is not enabled.",
enable: "Enable sync",
save: "Save and sync",
configured: "Cloud sync configuration saved.",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index ddb8e6078..2ce171ffc 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -682,6 +682,15 @@ sklm: {
allowInsecureHttp: "Allow HTTP for a trusted LAN address",
allowInsecureHttpWarning:
"HTTP does not encrypt WebDAV credentials. Enable only for a trusted LAN address; public HTTP endpoints are rejected.",
+ remoteMode: "Compatibilidad del servidor",
+ remoteModeHint:
+ "El modo estricto requiere escrituras condicionales fiables. Usa el modo de compatibilidad solo con servidores que ignoran If-Match/If-None-Match.",
+ remoteModeStrict: "CAS estricto (recomendado)",
+ remoteModeAppendOnly: "Modo de compatibilidad (solo anexar)",
+ appendOnlyWarning:
+ "Este modo es para servidores WebDAV que ignoran las escrituras condicionales. Inicializa la bóveda en un dispositivo antes de unir otros. Usa cabeceras de anexado por dispositivo y conserva el historial remoto; todos los dispositivos que compartan esta bóveda deben usar el modo de compatibilidad. Los cambios simultáneos pueden requerir revisión.",
+ appendOnlyConfirm:
+ "Este servidor no puede aplicar escrituras condicionales. El modo de compatibilidad conserva el historial, pero no ofrece un compare-and-swap atómico. ¿Continuar?",
username: "Username",
appPassword: "App password",
directory: "Remote directory",
@@ -703,6 +712,10 @@ sklm: {
testSuccess: "The server supports the required conditional writes.",
testUnsupported:
"The server did not prove reliable conditional writes; sync is not enabled.",
+ testAppendOnlySuccess:
+ "The server supports directory listing for append-only compatibility mode.",
+ testAppendOnlyUnsupported:
+ "The server did not prove directory listing for compatibility mode; sync is not enabled.",
enable: "Enable sync",
save: "Save and sync",
configured: "Cloud sync configuration saved.",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 4b796dcb5..a115eeb49 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -682,6 +682,15 @@ sklm: {
allowInsecureHttp: "Allow HTTP for a trusted LAN address",
allowInsecureHttpWarning:
"HTTP does not encrypt WebDAV credentials. Enable only for a trusted LAN address; public HTTP endpoints are rejected.",
+ remoteMode: "Compatibilité du serveur",
+ remoteModeHint:
+ "Le mode strict exige des écritures conditionnelles fiables. Utilisez le mode de compatibilité uniquement avec un serveur qui ignore If-Match/If-None-Match.",
+ remoteModeStrict: "CAS strict (recommandé)",
+ remoteModeAppendOnly: "Mode de compatibilité (ajout uniquement)",
+ appendOnlyWarning:
+ "Ce mode est destiné aux serveurs WebDAV qui ignorent les écritures conditionnelles. Initialisez le coffre sur un appareil avant d’en joindre d’autres. Il utilise des têtes d’ajout par appareil et conserve l’historique distant ; tous les appareils de ce coffre doivent utiliser le mode de compatibilité. Les modifications simultanées peuvent nécessiter une vérification.",
+ appendOnlyConfirm:
+ "Ce serveur ne peut pas appliquer les écritures conditionnelles. Le mode de compatibilité conserve l’historique, mais ne fournit pas de compare-and-swap atomique. Continuer ?",
username: "Username",
appPassword: "App password",
directory: "Remote directory",
@@ -703,6 +712,10 @@ sklm: {
testSuccess: "The server supports the required conditional writes.",
testUnsupported:
"The server did not prove reliable conditional writes; sync is not enabled.",
+ testAppendOnlySuccess:
+ "The server supports directory listing for append-only compatibility mode.",
+ testAppendOnlyUnsupported:
+ "The server did not prove directory listing for compatibility mode; sync is not enabled.",
enable: "Enable sync",
save: "Save and sync",
configured: "Cloud sync configuration saved.",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 7ad6fcb47..df88507f8 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -690,6 +690,15 @@ sklm: {
allowInsecureHttp: "Allow HTTP for a trusted LAN address",
allowInsecureHttpWarning:
"HTTP does not encrypt WebDAV credentials. Enable only for a trusted LAN address; public HTTP endpoints are rejected.",
+ remoteMode: "서버 호환 모드",
+ remoteModeHint:
+ "엄격 모드는 신뢰할 수 있는 조건부 쓰기를 요구합니다. If-Match/If-None-Match를 무시하는 서버에서만 호환 모드를 사용하세요.",
+ remoteModeStrict: "엄격한 CAS (권장)",
+ remoteModeAppendOnly: "호환 모드 (추가 전용)",
+ appendOnlyWarning:
+ "이 모드는 조건부 쓰기를 무시하는 WebDAV 서버용입니다. 다른 장치를 참여시키기 전에 한 장치에서 볼트를 초기화하세요. 장치별 추가 전용 헤드와 원격 기록을 사용하며, 이 볼트를 공유하는 모든 장치가 호환 모드를 사용해야 합니다. 동시 변경은 검토가 필요할 수 있습니다.",
+ appendOnlyConfirm:
+ "이 서버는 조건부 쓰기를 적용할 수 없습니다. 호환 모드는 기록을 보존하지만 원자적 compare-and-swap을 제공하지 않습니다. 계속하시겠습니까?",
username: "Username",
appPassword: "App password",
directory: "Remote directory",
@@ -711,6 +720,10 @@ sklm: {
testSuccess: "The server supports the required conditional writes.",
testUnsupported:
"The server did not prove reliable conditional writes; sync is not enabled.",
+ testAppendOnlySuccess:
+ "The server supports directory listing for append-only compatibility mode.",
+ testAppendOnlyUnsupported:
+ "The server did not prove directory listing for compatibility mode; sync is not enabled.",
enable: "Enable sync",
save: "Save and sync",
configured: "Cloud sync configuration saved.",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 0e2b93179..46a344d1d 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -689,6 +689,15 @@ sklm: {
allowInsecureHttp: "Allow HTTP for a trusted LAN address",
allowInsecureHttpWarning:
"HTTP does not encrypt WebDAV credentials. Enable only for a trusted LAN address; public HTTP endpoints are rejected.",
+ remoteMode: "Sunucu uyumluluğu",
+ remoteModeHint:
+ "Katı mod güvenilir koşullu yazma işlemleri gerektirir. Uyumluluk modunu yalnızca If-Match/If-None-Match'i yok sayan sunucularda kullanın.",
+ remoteModeStrict: "Katı CAS (önerilen)",
+ remoteModeAppendOnly: "Uyumluluk modu (yalnızca ekleme)",
+ appendOnlyWarning:
+ "Bu mod, koşullu yazmaları yok sayan WebDAV sunucuları içindir. Diğer cihazları katmadan önce kasayı bir cihazda başlatın. Cihaz başına ekleme amaçlı başlıklar kullanır ve uzak geçmişi korur; bu kasayı paylaşan tüm cihazlar uyumluluk modunu kullanmalıdır. Eşzamanlı değişiklikler incelenmeyi gerektirebilir.",
+ appendOnlyConfirm:
+ "Bu sunucu koşullu yazmaları uygulayamıyor. Uyumluluk modu geçmişi korur ancak atomik compare-and-swap sağlayamaz. Devam edilsin mi?",
username: "Kullanıcı adı",
appPassword: "Uygulama parolası",
directory: "Uzak dizin",
@@ -708,6 +717,8 @@ sklm: {
test: "Sunucuyu test et",
testSuccess: "Sunucu gerekli koşullu yazma işlemlerini destekliyor.",
testUnsupported: "Sunucu güvenilir koşullu yazmayı kanıtlayamadı; senkronizasyon etkinleştirilmedi.",
+ testAppendOnlySuccess: "Sunucu, ekleme amaçlı uyumluluk modu için dizin listelemeyi destekliyor.",
+ testAppendOnlyUnsupported: "Sunucu, uyumluluk modu için dizin listelemeyi kanıtlayamadı; senkronizasyon etkinleştirilmedi.",
enable: "Senkronizasyonu etkinleştir",
save: "Kaydet ve senkronize et",
configured: "Bulut senkronizasyonu yapılandırması kaydedildi.",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 6d81a7f7d..d0dc5a068 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -678,6 +678,12 @@ sklm: {
endpointPlaceholder: "https://dav.example.com/",
allowInsecureHttp: "允许在受信任的内网地址使用 HTTP",
allowInsecureHttpWarning: "HTTP 不会加密 WebDAV 凭据。仅对你控制的受信任内网地址启用;公网 HTTP 地址会被拒绝。",
+ remoteMode: "服务器兼容模式",
+ remoteModeHint: "严格模式要求服务器可靠支持条件写入。仅当服务器忽略 If-Match/If-None-Match 时使用兼容模式。",
+ remoteModeStrict: "严格 CAS(推荐)",
+ remoteModeAppendOnly: "兼容模式(仅追加头)",
+ appendOnlyWarning: "此模式用于忽略条件写入的 WebDAV 服务器。请先在一台设备上初始化保管库,再让其他设备加入。它为每台设备使用独立的追加式头并保留远程历史;共享此保管库的所有设备都必须使用兼容模式,并发修改仍可能需要处理冲突。",
+ appendOnlyConfirm: "此服务器无法执行条件写入。兼容模式会保留历史,但无法提供原子比较并交换。要继续吗?",
username: "用户名",
appPassword: "应用密码",
directory: "远程目录",
@@ -697,6 +703,8 @@ sklm: {
test: "测试服务器",
testSuccess: "服务器支持所需的条件写入。",
testUnsupported: "服务器未能证明支持可靠的条件写入,未启用同步。",
+ testAppendOnlySuccess: "服务器支持兼容模式所需的目录列表。",
+ testAppendOnlyUnsupported: "服务器未能证明支持兼容模式所需的目录列表,未启用同步。",
enable: "启用同步",
save: "保存并同步",
configured: "云同步配置已保存。",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 1e832c8c7..645e26fb3 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -678,6 +678,12 @@ sklm: {
endpointPlaceholder: "https://dav.example.com/",
allowInsecureHttp: "允許在受信任的內網位址使用 HTTP",
allowInsecureHttpWarning: "HTTP 不會加密 WebDAV 憑據。僅對你控制的受信任內網位址啟用;公網 HTTP 位址會被拒絕。",
+ remoteMode: "伺服器相容模式",
+ remoteModeHint: "嚴格模式要求伺服器可靠支援條件寫入。僅在伺服器忽略 If-Match/If-None-Match 時使用相容模式。",
+ remoteModeStrict: "嚴格 CAS(推薦)",
+ remoteModeAppendOnly: "相容模式(僅追加標頭)",
+ appendOnlyWarning: "此模式適用於忽略條件寫入的 WebDAV 伺服器。請先在一部裝置上初始化保管庫,再讓其他裝置加入。它會為每部裝置使用獨立的追加式標頭並保留遠端歷史;共用此保管庫的所有裝置都必須使用相容模式,並行修改仍可能需要處理衝突。",
+ appendOnlyConfirm: "此伺服器無法執行條件寫入。相容模式會保留歷史,但無法提供原子比較並交換。要繼續嗎?",
username: "使用者名稱",
appPassword: "應用程式密碼",
directory: "遠端目錄",
@@ -697,6 +703,8 @@ sklm: {
test: "測試伺服器",
testSuccess: "伺服器支援必要的條件寫入。",
testUnsupported: "伺服器未能證明支援可靠的條件寫入,因此未啟用同步。",
+ testAppendOnlySuccess: "伺服器支援相容模式所需的目錄列表。",
+ testAppendOnlyUnsupported: "伺服器未能證明支援相容模式所需的目錄列表,因此未啟用同步。",
enable: "啟用同步",
save: "儲存並同步",
configured: "雲端同步設定已儲存。",
diff --git a/packages/shared/src/types/config-sync.ts b/packages/shared/src/types/config-sync.ts
index 2d330b84d..46bfd96a5 100644
--- a/packages/shared/src/types/config-sync.ts
+++ b/packages/shared/src/types/config-sync.ts
@@ -35,6 +35,8 @@ export type ConfigSyncStatus =
| "paused"
| "error";
+export type ConfigSyncRemoteMode = "strict" | "appendOnly";
+
export type ConfigSyncCategorySelection = Record<ConfigSyncCategory, boolean>;
export type ConfigSyncPreferences = {
@@ -43,6 +45,7 @@ export type ConfigSyncPreferences = {
directory: string;
deviceLabel: string;
allowInsecureHttp?: boolean;
+ remoteMode?: ConfigSyncRemoteMode;
categories: ConfigSyncCategorySelection;
includeSecrets: boolean;
includeMemory: boolean;
@@ -103,6 +106,7 @@ export type ConfigSyncState = {
deviceLabel?: string;
/** True only when the configured WebDAV endpoint is an acknowledged LAN HTTP target. */
allowInsecureHttp?: boolean;
+ remoteMode: ConfigSyncRemoteMode;
categories: ConfigSyncCategorySelection;
includeSecrets: boolean;
includeMemory: boolean;
@@ -126,6 +130,7 @@ export type ConfigSyncConfigureInput = {
/** Required when creating or unlocking the encrypted vault. */
backupPassword: string;
allowInsecureHttp?: boolean;
+ remoteMode?: ConfigSyncRemoteMode;
categories?: Partial<ConfigSyncCategorySelection>;
includeSecrets?: boolean;
includeMemory?: boolean;