Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

calendar wip

oxydizerd5e7f09bbf31
diff --git a/docs/plans/calendar-accounts.md b/docs/plans/calendar-accounts.md
new file mode 100644
index 0000000..abd5c5d
--- /dev/null
+++ b/docs/plans/calendar-accounts.md
@@ -0,0 +1,149 @@
+# Calendar Phase 0: test accounts and OAuth registration
+
+Checked against provider documentation on 2026-10-31. These steps prepare the
+real-account qualification in [Phase 0](calendar-phase0.md) of the
+[calendar plan](calendar.md). The current prototype does **not** implement
+browser sign-in or token storage yet; registering clients does not make the
+local probes contact either provider.
+
+## Prepare three test accounts
+
+Use a dedicated Google account, a dedicated personal Microsoft account with
+Outlook.com Calendar, and an organization-approved Microsoft 365 work/school
+test account with a working Exchange Online mailbox. Verify each can open its
+calendar in the provider's browser UI. An Entra directory user alone does not
+establish that a calendar mailbox is available. [Microsoft mailbox support](https://learn.microsoft.com/en-us/graph/outlook-mail-concept-overview)
+
+Keep these accounts free of real appointments. In each browser calendar,
+create an owned secondary calendar named `RediWM Phase 0` and retain the
+account's primary calendar for primary-calendar cases. Use events without
+attendees initially. Primary and secondary calendars must both be tested;
+passing a personal Microsoft account does not qualify a work/school account.
+
+Register development clients under an owner who will retain access to the
+Google project and Microsoft tenant. If there is no suitable Microsoft test
+tenant or mailbox, record that prerequisite as pending and arrange access
+with its administrator; a personal account cannot substitute for it.
+
+## Google
+
+1. Open the [Google Cloud console](https://console.cloud.google.com/), create
+ or select a development project, and enable **Google Calendar API** under
+ **APIs & Services → Library**. Record the project ID and owner.
+2. Open **Google Auth platform → Branding**. If prompted, choose **Get
+ started**; enter an app name such as `RediWM Calendar Phase 0`, support
+ email and developer contact. Choose **External** as the audience.
+3. Under **Audience**, keep the project in **Testing** and add the dedicated
+ Google account under **Test users**. Under **Data Access**, add the scopes
+ below. [Google consent configuration](https://developers.google.com/workspace/guides/configure-oauth-consent)
+4. Under **Google Auth platform → Clients → Create client**, select
+ **Desktop app**, name it, and create it. Record its public client ID.
+ The eventual harness will open the system browser and use authorization
+ code flow with PKCE and a loopback callback. Google permits a desktop
+ callback such as `http://127.0.0.1:<port>`; the harness will choose and bind
+ the port. [Google desktop registration and flow](https://developers.google.com/identity/protocols/oauth2/native-app)
+
+The proposed **native Calendar REST** access is:
+
+| Scope | Purpose |
+| --- | --- |
+| `https://www.googleapis.com/auth/calendar.calendarlist.readonly` | Discover calendars already available to the account |
+| `https://www.googleapis.com/auth/calendar.events` | Read and change events |
+| `openid email` | Identify the signed-in account; requested by the future sign-in harness |
+
+Calendar creation and sharing are outside this initial scope. Creating the
+test secondary calendar in the browser avoids requiring calendar-management
+permissions just to prepare the fixture. [Calendar scope reference](https://developers.google.com/workspace/calendar/api/auth)
+
+EDS uses Google's CalDAV interface, so these REST scopes do **not** establish
+that EDS will work. Its reduced-scope discovery, sign-in and renewal remain
+qualification gates. Enable Google's CalDAV API in the development project
+when running that candidate, following the [CalDAV setup guide](https://developers.google.com/workspace/calendar/caldav/v2/guide).
+
+External projects in Testing receive seven-day refresh tokens when calendar
+access is requested. Record this expected expiry separately from a backend
+failure. Production publishing and applicable OAuth verification must be
+completed before release; Testing is sufficient for the development runs.
+[Google refresh-token expiry](https://developers.google.com/identity/protocols/oauth2#expiration),
+[verification requirements](https://developers.google.com/workspace/guides/configure-oauth-consent#scope_categories)
+
+## Microsoft: one registration, two account classes
+
+1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/)
+ in a tenant where you may register applications. If registration is
+ restricted, ask the tenant administrator to create this development client
+ or grant the appropriate developer role.
+2. Open **Entra ID → App registrations → New registration**. Name the app
+ `RediWM Calendar Phase 0`. Select the audience that includes **any Entra ID
+ tenant and personal Microsoft accounts**; older portal wording is
+ **Accounts in any organizational directory and personal Microsoft
+ accounts**. Register and record the **Application (client) ID**, owning
+ **Directory (tenant) ID** and registration owner. [App registration](https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-register-app)
+3. Under **Authentication → Add a platform → Mobile and desktop
+ applications**, add **`http://localhost`** as the system-browser redirect
+ and save. This configures a native/public-client callback. The eventual
+ harness will use a loopback listener; localhost matching permits an
+ ephemeral port. Keep the callback path consistent with the registration.
+ [Desktop configuration](https://learn.microsoft.com/en-us/entra/identity-platform/scenario-desktop-app-configuration),
+ [localhost matching](https://learn.microsoft.com/en-us/entra/identity-platform/reply-url#localhost-exceptions)
+4. Under **API permissions → Add a permission → Microsoft Graph → Delegated
+ permissions**, add **`Calendars.ReadWrite`**. Add the OIDC permissions
+ **`openid`**, **`profile`** and **`offline_access`** for sign-in, account
+ display and renewal. Remove an unused default `User.Read` permission if
+ present: this prototype intends to use the ID token for account identity,
+ rather than reading the user's Graph profile. [Permission setup](https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-configure-app-access-web-apis),
+ [OIDC permissions](https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc)
+
+The future harness must request those scopes in its authorization-code flow
+with PKCE, using the `common` authority to allow both account classes. Do not
+create a client secret for this desktop client. The flow obtains refresh
+tokens through `offline_access`; enabling only a permission in the portal
+does not replace requesting it during authorization. [Microsoft code flow](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow)
+
+`Calendars.ReadWrite` must be **delegated**, not the application permission
+of the same name. It supports personal accounts and does not itself require
+administrator consent, but organizational consent policy and conditional
+access can still require approval or prevent sign-in. Obtain the test
+tenant's required approval and record the result; do not relax its policies
+to claim support. [Calendar permissions](https://learn.microsoft.com/en-us/graph/permissions-reference#calendarsreadwrite)
+
+EDS/evolution-ews must separately demonstrate that its initial sign-in and
+refresh use only the agreed permissions. Its stock OAuth adapter requests
+broader permissions; creating this registration alone does not narrow that
+adapter. [Current Microsoft365 adapter](https://raw.githubusercontent.com/GNOME/evolution-ews/master/src/Microsoft365/common/e-oauth2-service-microsoft365.c)
+
+## What to record now
+
+Record registration ownership, public client IDs, account classes available,
+configured redirect and scope names, and whether tenant approval is pending.
+Public client IDs identify apps; they are not account passwords or tokens.
+Google's desktop configuration may also contain a field named `client_secret`;
+a desktop app cannot keep that field confidential, and it must never replace
+PKCE. Keep downloaded credential files out of the repository and chat.
+[Google public-client model](https://developers.google.com/identity/protocols/oauth2/native-app)
+
+Do not paste passwords, authorization codes, access tokens or refresh tokens
+into chat, logs, argv or plaintext prototype files. The real-account harness
+still needs browser authorization and qualified keyring storage before any
+token can be used. No manual token export is needed for this preparation.
+
+## Qualification once the real-account harness exists
+
+For each of the three account classes and each backend candidate under test:
+
+- Record package versions, requested/granted scope names and the calendar
+ capability matrix; capture no tokens or private calendar contents.
+- Create, fetch, edit and delete a uniquely named event from the harness;
+ make a browser-side edit and confirm it arrives locally. Repeat on primary
+ and secondary owned calendars.
+- Create a recurring series, move one occurrence and delete another; verify
+ original occurrence identity and whole-series reads, including Graph masters.
+- Edit while offline, restart the prototype, reconnect and confirm one
+ remote update. Simulate a lost create response and verify no duplicate.
+- Make concurrent browser/local edits and verify a visible conflict without
+ silently losing either version. Exercise a moved occurrence at the cache
+ boundary and invalid sync state while pending work exists.
+- Exercise token renewal, cancellation, revocation/reconnect and a locked
+ keyring. Confirm renewal does not broaden scopes or activate mail/tasks.
+- Record pass/fail/pending evidence in [the Phase 0 record](calendar-phase0.md).
+ Browser login alone and the current local probes cannot pass these gates.
diff --git a/docs/plans/calendar-phase0-local.json b/docs/plans/calendar-phase0-local.json
new file mode 100644
index 0000000..fd17a6f
--- /dev/null
+++ b/docs/plans/calendar-phase0-local.json
@@ -0,0 +1,170 @@
+{
+ "schema_version": 1,
+ "scope": "local_dependency_prototype",
+ "backend_decision": "pending",
+ "phase0_complete": false,
+ "inventory": {
+ "packages": {
+ "sqlite3": {
+ "status": "available",
+ "version": "3.54.0"
+ },
+ "libical": {
+ "status": "available",
+ "version": "4.0.7"
+ },
+ "libcurl": {
+ "status": "available",
+ "version": "8.23.0"
+ },
+ "libecal-2.0": {
+ "status": "available",
+ "version": "3.60.2"
+ },
+ "libedataserver-1.2": {
+ "status": "available",
+ "version": "3.60.2"
+ },
+ "libsecret-1": {
+ "status": "available",
+ "version": "0.21.8.2"
+ }
+ },
+ "provider_modules": [
+ "libecalbackendcaldav.so"
+ ],
+ "tools": {
+ "cc": true,
+ "pkg-config": true,
+ "dbus-daemon": true,
+ "gdbus": true,
+ "glib-compile-schemas": true
+ },
+ "keyring_access": "not_tested",
+ "provider_access": "not_tested"
+ },
+ "probes": {
+ "native": {
+ "status": "pass",
+ "ical_roundtrip": true,
+ "dst_master_expansion": true,
+ "exception_identity_preservation": true,
+ "sqlite_rollback": true,
+ "pending_survives_cache_refresh_and_reopen": true,
+ "exception_overlay_applied": false,
+ "provider_qualification": false
+ },
+ "eds": {
+ "status": "pass",
+ "write": {
+ "status": "pass",
+ "scope": "eds_local_store",
+ "stage": "write",
+ "series_edit": true,
+ "moved_occurrence": true,
+ "provider_qualification": false
+ },
+ "after_service_restart": {
+ "status": "pass",
+ "scope": "eds_local_store",
+ "stage": "read",
+ "series_edit": true,
+ "moved_occurrence": true,
+ "provider_qualification": false
+ },
+ "runtime": "local module only; backend-per-process=0; no activation services",
+ "idle": {
+ "seconds": 15.004,
+ "processes": {
+ "bus": {
+ "memory": {
+ "Rss_kib": 4468,
+ "Pss_kib": 822,
+ "Private_Clean_kib": 192,
+ "Private_Dirty_kib": 452
+ },
+ "threads": [
+ {
+ "name": "dbus-daemon",
+ "voluntary_delta": 0,
+ "involuntary_delta": 0
+ }
+ ],
+ "new_threads": 0,
+ "exited_threads": 0
+ },
+ "registry": {
+ "memory": {
+ "Rss_kib": 20124,
+ "Pss_kib": 5581,
+ "Private_Clean_kib": 108,
+ "Private_Dirty_kib": 3132
+ },
+ "threads": [
+ {
+ "name": "evolution-sourc",
+ "voluntary_delta": 0,
+ "involuntary_delta": 0
+ },
+ {
+ "name": "gmain",
+ "voluntary_delta": 0,
+ "involuntary_delta": 0
+ },
+ {
+ "name": "pool-spawner",
+ "voluntary_delta": 0,
+ "involuntary_delta": 0
+ },
+ {
+ "name": "gdbus",
+ "voluntary_delta": 0,
+ "involuntary_delta": 0
+ }
+ ],
+ "new_threads": 0,
+ "exited_threads": 1
+ },
+ "calendar": {
+ "memory": {
+ "Rss_kib": 22516,
+ "Pss_kib": 8004,
+ "Private_Clean_kib": 1272,
+ "Private_Dirty_kib": 4368
+ },
+ "threads": [
+ {
+ "name": "evolution-calen",
+ "voluntary_delta": 0,
+ "involuntary_delta": 0
+ },
+ {
+ "name": "gmain",
+ "voluntary_delta": 0,
+ "involuntary_delta": 0
+ },
+ {
+ "name": "pool-spawner",
+ "voluntary_delta": 0,
+ "involuntary_delta": 0
+ },
+ {
+ "name": "gdbus",
+ "voluntary_delta": 0,
+ "involuntary_delta": 0
+ },
+ {
+ "name": "evolution-calen",
+ "voluntary_delta": 0,
+ "involuntary_delta": 0
+ }
+ ],
+ "new_threads": 0,
+ "exited_threads": 3
+ }
+ }
+ },
+ "provider_qualification": false
+ }
+ }
+}
diff --git a/docs/plans/calendar-phase0.md b/docs/plans/calendar-phase0.md
new file mode 100644
index 0000000..795d81a
--- /dev/null
+++ b/docs/plans/calendar-phase0.md
@@ -0,0 +1,119 @@
+# Calendar Phase 0 evidence
+
+Started 2026-10-31 against repository HEAD `805d866`. **Backend undecided;
+Phase 0 is not complete.** This record implements the first local evaluation
+slice of the [calendar plan](calendar.md). Reproduction commands are in the
+[probe README](../../tools/calendar/README.md); the
+[account setup guide](calendar-accounts.md) prepares the remaining live runs.
+
+## Local dependencies and probes
+
+The host is Arch Linux x86_64. EDS was absent from the installed development
+environment; a cached package was extracted under `/tmp` without installing
+packages or changing host services. A private bus, private HOME/XDG directories
+and only EDS's local calendar module were used. No real accounts were contacted.
+
+| Dependency | Observed version | Source / package license metadata |
+| --- | --- | --- |
+| SQLite | 3.54.0 (`3.54.0-1`) | Installed; `LicenseRef-Sqlite` |
+| libical | 4.0.7 (`4.0.7-1`) | Installed; `LGPL-2.1-only`, `MPL-2.0` |
+| libcurl | 8.23.0 (`8.23.0-1`) | Installed, inventoried only; `curl` |
+| libsecret | 0.21.8.2 (`0.21.8.2-1`) | Installed, inventoried only; `LGPL-2.1-or-later` |
+| Evolution Data Server | 3.60.2 (`3.60.2-5`) | Extracted Arch package; `LGPL-2.0-only AND LGPL-2.1-or-later` |
+
+These are observed package metadata, not a completed redistribution/notices
+audit. Other release-family versions and Microsoft365 package dependencies
+still need qualification. The extracted EDS package contains the CalDAV module
+but no Microsoft365 module. Absence here does not establish distribution-wide
+unavailability: evolution-ews is a separate package.
+
+Archive: `evolution-data-server-3.60.2-5-x86_64.pkg.tar.zst`.
+SHA-256: `727827aed97c0c18c21f83fc27b0834be5b56bc0d9c9e5462cc6bd8482e5866f`.
+
+| Check | Result | Limit |
+| --- | --- | --- |
+| Native `.ics` round trip | Pass: embedded timezone, recurrence, moved/cancelled original identities and unknown metadata retained | No provider conversion or detached-exception overlay |
+| Native recurrence primitive | Pass: bounded master expansion, EXDATE and Auckland DST's 23-hour interval | Not a complete agenda expansion engine; other date/time cases pending |
+| Native SQLite primitive | Pass: rollback, reopen and pending/base-revision retention after synthetic cache replacement | No HTTP, conflict resolver, crash injection or production schema |
+| EDS local CRUD | Pass: create recurring event, edit series, move occurrence and read by original identity | No remote backend or OAuth |
+| EDS restart persistence | Pass after stopping/restarting bus, registry and calendar factory | Orderly restart, not process death during a write or power-loss recovery |
+| Harness timeout/cleanup | Pass: timeout with exited parent and live descendant; teardown of SIGTERM-ignoring descendant | Synthetic owned process groups only |
+| Keyring | Library available; access, unlock and token storage not tested | Required before live sign-in |
+
+Both C probes compile with `-std=c11 -Wall -Wextra -Werror`. The native probe
+also passed an AddressSanitizer/UndefinedBehaviorSanitizer run and refused reuse
+of its populated database without changing the stored bytes.
+
+## Limited idle observation
+
+The [recorded JSON](calendar-phase0-local.json) comes from the local probes with
+`--idle-seconds 15`. The sample lasted 15.004 seconds, after the client closed
+and a one-second settling interval. The calendar factory used
+`--keep-running --backend-per-process=0`; registry modules were disabled and only
+the local calendar module was loaded.
+
+| Process | PSS, KiB | RSS, KiB | Surviving threads' voluntary / involuntary switches | Threads exited during sample |
+| --- | ---: | ---: | --- | ---: |
+| Private bus | 822 | 4,468 | 0 / 0 | 0 |
+| EDS source registry | 5,581 | 20,124 | 0 / 0 | 1 |
+| EDS calendar factory | 8,004 | 22,516 | 0 / 0 | 3 |
+
+No new threads appeared. Final counters for departed threads are unavailable;
+the zero deltas must not be described as zero total process wakeups. This is a
+local-store observation, not a production footprint or performance acceptance
+result. Repeat with the selected provider modules, subscriptions, keyring and
+scheduled refresh enabled. There is no native service to compare yet.
+
+## Provider qualification matrix
+
+Client registrations and dedicated accounts are not yet prepared. The current
+tools have no browser sign-in, token storage or live-provider commands. Follow
+the [setup guide](calendar-accounts.md); do not export tokens into files or chat.
+
+| Gate | Google | Personal Outlook | Microsoft 365 work/school |
+| --- | --- | --- | --- |
+| Public client registration and dedicated mailbox/calendar | Pending | Pending | Pending |
+| Calendar-only consent, discovery, refresh and reconnect | Pending | Pending | Pending |
+| Keyring storage, locked/missing keyring and revocation | Pending | Pending | Pending |
+| Primary and secondary owned calendar round trips | Pending | Pending | Pending |
+| Recurring master and moved/deleted exception | Pending | Pending | Pending |
+| Offline write survives restart and invalid sync state | Pending | Pending | Pending |
+| Concurrent edit surfaces a conflict | Pending | Pending | Pending |
+| Lost response does not duplicate a create | Pending | Pending | Pending |
+| Range-boundary movement and coverage behavior | Pending | Pending | Pending |
+
+EDS remains a candidate. Its local baseline passes, but narrow-scope credential
+integration and Graph behavior are not demonstrated. SQLite/libical primitives
+also pass; that is not evidence of a working native sync engine. Neither
+candidate has passed the backend-selection gate.
+
+## Decisions and next work
+
+1. Prepare the registrations and three account classes, and inventory the
+ packaged Microsoft365 backend on supported distributions. Complete dependency
+ and license-notice records.
+2. Prototype the keyring client and browser/PKCE flow in the isolated tool,
+ then prove EDS's reduced-scope initial sign-in **and refresh** for both
+ providers. Keep any native REST details separate from EDS/CalDAV behavior.
+3. Run the provider matrix using dedicated calendars, including offline and
+ concurrent modifications. Record failure evidence rather than filling cells
+ from source-code inspection or fake servers.
+4. Choose the backend and freeze the app/service contract, offline horizon and
+ supervision policy. Unix socket transport remains a proposal. The existing
+ helper manager does not restart exited children; supervisor/backoff,
+ compositor reconnection, single-writer ownership and logout teardown still
+ need an executable prototype. Notification IDs must remain scoped to a
+ notification-server lifetime separately from durable reminder identities.
+
+## Repository validation
+
+Debug build, ReleaseSafe build and `zig build test` pass. The popup-only suite
+at scales 1 and 1.5 passes, including private German locale names and live format
+reload. The full `tests/calendar_popup.py` suite fails at line 262,
+`assert selected == "C"`, during Settings locale selection. An independently
+built, clean detached HEAD worktree at `805d866` reproduces the same assertion;
+this is pre-existing. No production calendar or Settings code was changed.
+
+Run logs are under `/tmp/rediwm-calendar-*`; those paths are temporary. The
+JSON and this record retain the local evidence after scratch directories are
+removed. Full integration and live-provider completion remain separate gates.
diff --git a/docs/plans/calendar.md b/docs/plans/calendar.md
index e0ef570..825bc52 100644
--- a/docs/plans/calendar.md
+++ b/docs/plans/calendar.md
@@ -1,8 +1,11 @@
# Calendar integration plan
-Status: draft, 2026-10-25. The first release must support **Google Calendar
-and Outlook/Microsoft 365 together**, including personal Microsoft accounts
-and work or school accounts. CalDAV follows after those providers.
+Status: Phase 0 started, 2026-10-31; backend undecided. Track evidence and open
+gates in [the Phase 0 record](calendar-phase0.md), using the noninstalled
+[prototype tools](../../tools/calendar/README.md). The first release must
+support **Google Calendar and Outlook/Microsoft 365 together**, including
+personal Microsoft accounts and work or school accounts. General CalDAV
+account support follows after those providers.
Build a native Calendar application, an agenda in the taskbar clock popup,
and a separate service for storage, synchronization and reminders. Use
@@ -87,11 +90,21 @@ References: [EDS client API](https://gnome.pages.gitlab.gnome.org/evolution-data
Accept EDS only if the packaged versions can support calendar-only browser
sign-in, both Microsoft account types, offline writes, recurrence exceptions,
controlled service lifetime and an acceptable idle footprint without an
-Evolution window or toolkit-owned account dialogs. Its current Google OAuth
-implementation requests mail, contacts and tasks as well as calendars, so a
-narrower credential integration must be proved. Qualify the Microsoft
-**Graph** backend and its actual distribution availability.
-[EDS Google OAuth implementation](https://raw.githubusercontent.com/GNOME/evolution-data-server/master/src/libedataserver/e-oauth2-service-google.c)
+Evolution window or toolkit-owned account dialogs. Its Google OAuth defaults
+request mail, contacts and tasks as well as calendars; evolution-ews also
+requests broader Microsoft permissions, including during token refresh.
+Prove reduced scopes through sign-in, resource discovery, expiry/refresh and
+reconnect for **both providers**, without activating unrelated mail, contacts
+or tasks. Qualify the Microsoft **Graph** backend and its actual distribution
+availability. [EDS Google OAuth implementation](https://raw.githubusercontent.com/GNOME/evolution-data-server/master/src/libedataserver/e-oauth2-service-google.c),
+[Microsoft OAuth implementation](https://raw.githubusercontent.com/GNOME/evolution-ews/master/src/Microsoft365/common/e-oauth2-service-microsoft365.c)
+
+EDS's Google backend uses CalDAV. The REST scopes and sync mechanics below
+describe the native candidate; EDS must demonstrate the same user-visible
+correctness through its own APIs. Test the proposed reduced Google scopes
+against the packaged CalDAV adapter; Calendar REST behavior alone does not
+prove that integration. Supporting this adapter does not qualify arbitrary
+CalDAV providers. [EDS Google backend](https://raw.githubusercontent.com/GNOME/evolution-data-server/master/src/modules/google-backend/module-google-backend.c)
Choose one backend after the prototype. With EDS, its store is authoritative;
any RediWM sidecar stores only app-specific state the backend cannot own.
@@ -115,9 +128,9 @@ scopes needed for sign-in. Browser-based authorization keeps MFA with the
provider. [Google desktop OAuth](https://developers.google.com/identity/protocols/oauth2/native-app),
[Microsoft authorization code flow](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow)
-Google's initial scope set should cover calendar-list discovery and event
-read/write access; request calendar-management/sharing permissions only when
-those features arrive. Complete the applicable production consent and
+For the native candidate, Google's initial scopes should cover calendar-list
+discovery and event read/write access; request calendar-management/sharing
+permissions only when those features arrive. Complete the applicable production consent and
verification work. An external app left in Google's Testing state generally
gets seven-day refresh tokens for calendar access, which is not a usable
release configuration. [Google scopes](https://developers.google.com/workspace/calendar/api/auth),
@@ -139,7 +152,12 @@ authentication; never silently store tokens as plaintext. Keep secrets out
of config files, logs, argv, UI arenas and ordinary IPC snapshots.
[Secret Service API](https://specifications.freedesktop.org/secret-service/latest/)
-| Provider | Required synchronization behavior |
+Both backends must preserve pending writes, recover from invalid sync state,
+track deletions and permission changes, and expose accurate cached coverage.
+For EDS, qualify these through its adapter and store; do not add a second
+RediWM sync engine around it. Native provider implementation details follow:
+
+| Provider | Native synchronization behavior |
| --- | --- |
| Google | Paginated initial sync, per-calendar sync tokens, deletions and permission changes; recover invalid tokens with a new remote snapshot while preserving unsent local changes |
| Microsoft | Fixed-range `calendarView/delta` where supported; qualify secondary calendars and use bounded calendar-view snapshot/diff otherwise; extend/rebuild coverage as the range advances |
@@ -212,6 +230,15 @@ window lifetime. Define startup, restart, logout and nested-session isolation
explicitly; use a single database writer and reminder delivery target. The
greeter must never activate the service, keyring, account setup or cache.
+Phase 0 must choose one supervisor and document its ownership boundary.
+The current session helper manager logs exits and does not restart helpers;
+tracking a child is insufficient. Require bounded restart backoff, a visible
+failure state after repeated crashes, and bounded logout teardown with no
+respawn during shutdown. Compositor restart must reconnect to the existing
+owner or recover it without a second writer or reminder sender. Subscriptions
+must reconnect and refresh snapshots after either process restarts. Verify
+the chosen policy before relying on reminders with the app closed.
+
If EDS is selected, RediWM owns its wrapper and subscriptions. Logout must
release those without terminating shared EDS or keyring processes used by
other applications. Coordinate reminder ownership so an existing backend
@@ -221,6 +248,10 @@ Persist snoozed/dismissed alarms and a delivery ledger keyed by event
occurrence and alarm. Recalculate deadlines after edits, deletions, resume,
time-zone changes and wall-clock adjustments. Use notification replacement
and durable delivery state to avoid repeated alarms after reconnect/restart.
+Notification IDs are temporary: scope each replacement mapping to the
+notification server's D-Bus owner/generation and discard it when that owner
+changes. Persist occurrence/alarm identity separately; never reuse a saved
+numeric notification ID against a restarted server, which can reuse IDs.
Keep a missed-reminder list because notification toast lifetime is not a
durable record. Local snoozes need not change other devices' reminders.
@@ -274,13 +305,14 @@ rendering notes before implementation.
## Delivery phases and completion criteria
1. **Phase 0 — Backend and account prototype.** Compare EDS and native dependencies,
- qualify Google plus both Microsoft account types, calendar-only consent,
- keyring access and provider round-trips. Exercise one recurring event,
- offline edit and concurrent modification per provider, including primary
+ qualify Google plus both Microsoft account types, calendar-only consent
+ and refresh, keyring access and provider round-trips. Exercise one recurring
+ event, offline edit and concurrent modification per provider, including primary
and secondary owned calendars and Graph series-master loading. Record process
footprint, idle wakes, package versions, license notices, registration
- ownership, cache horizon and transport choice. Completion means one chosen
- backend with demonstrated behavior; mock data alone does not pass this gate.
+ ownership, cache horizon, supervisor/reconnect policy and transport choice.
+ Completion means one chosen backend with demonstrated behavior; mock data
+ alone does not pass this gate.
2. **Phase 1 — Local calendar foundation.** Add service/model, durable local calendar,
native month/agenda views, editor, common recurrence and `.ics` preview,
import/export. Completion means local events survive restarts and the app
@@ -327,11 +359,15 @@ remote deletion, lost responses, pagination, invalid sync state, advancing
Graph coverage, rate limits, token revocation, locked keyring, permission
changes, conflicting edits, crash recovery and unsent edits on disconnect.
-Exercise popup/app updates while requests are pending, service restarts,
-close/reopen, stable selection, keyboard navigation, themes and scales 1/1.5.
+Exercise popup/app updates while requests are pending, service and compositor
+restarts, close/reopen, stable selection, keyboard navigation, themes and
+scales 1/1.5.
Test reminder cancellation, duplicate prevention, snooze, clock changes,
-resume, DND, lock and multiple/nested sessions. Measure per-thread wakeups
-with no accounts, idle local calendars and scheduled remote sync separately.
+resume, DND, lock and multiple/nested sessions. Restart the notification server
+while unrelated notifications exist; stale replacement IDs must not replace
+them or trigger duplicate reminders. Exercise supervisor backoff and logout
+during a pending restart. Measure per-thread wakeups with no accounts, idle
+local calendars and scheduled remote sync separately.
Implementation gates follow [`TESTING.md`](../../TESTING.md): Debug and
ReleaseSafe builds, `zig build test`, calendar app/service fixtures and
@@ -339,6 +375,6 @@ ReleaseSafe builds, `zig build test`, calendar app/service fixtures and
notification, lock/greeter, session lifecycle, activation and i18n suites.
Compare failures with a clean HEAD worktree before calling them regressions.
-The next implementation step is Phase 0. Its backend decision and real Google,
-personal Outlook and Microsoft 365 results determine the work estimate for
-the remaining phases.
+Phase 0 is in progress; local dependency/prototype results do not complete it.
+Its backend decision and real Google, personal Outlook and Microsoft 365
+results determine the work estimate for the remaining phases.
diff --git a/tools/calendar/README.md b/tools/calendar/README.md
new file mode 100644
index 0000000..46db531
--- /dev/null
+++ b/tools/calendar/README.md
@@ -0,0 +1,101 @@
+# Calendar Phase 0 probes
+
+Noninstalled backend evaluation tools for the [calendar plan](../../docs/plans/calendar.md).
+The [qualification record](../../docs/plans/calendar-phase0.md) tracks results;
+[account setup](../../docs/plans/calendar-accounts.md) prepares the later live runs.
+These tools use synthetic local data. They do not implement OAuth, provider
+sync, a production store, service supervision or the app/popup integration.
+
+## Run
+
+From the repository root:
+
+```sh
+python3 tools/calendar/probe.py inventory
+python3 tools/calendar/probe.py local --backend native
+python3 tools/calendar/probe.py local --backend eds --idle-seconds 15
+python3 tools/calendar/probe.py local --backend all --output /tmp/calendar-local.json
+```
+
+Python 3, a C compiler and `pkg-config` are required. The native probe links
+SQLite and libical. EDS additionally needs `libecal-2.0`, `libedataserver-1.2`,
+the source-registry/calendar-factory executables and local calendar module,
+`dbus-daemon`, `gdbus` and `glib-compile-schemas`. The inventory reports libcurl,
+libsecret and detected CalDAV/Microsoft365 modules separately; library presence
+does not demonstrate HTTP synchronization, keyring access or provider support.
+
+The default `local` backend selection is `all`. Exit codes are `0` for the
+requested local checks passing, `1` for a probe failure and `2` for unavailable
+backend development dependencies. `inventory` reports missing dependencies
+without failing. Every report retains `phase0_complete: false` and
+`backend_decision: pending`. An output report is created privately and is never
+overwritten. The repository build and installed programs do not depend on EDS
+or these tools.
+
+## Test an extracted EDS package
+
+No host package installation is necessary when a compatible binary package is
+already available. Extract it into a scratch directory and pass its `usr`
+directory. Its shared-library dependencies must also be available; a package
+from a different distribution or ABI is not interchangeable.
+
+For the cached Arch package used in the first run:
+
+```sh
+umask 077
+calendar_eds_root=$(mktemp -d /tmp/calendar-eds.XXXXXX)
+tar -xf /var/cache/pacman/pkg/evolution-data-server-3.60.2-5-x86_64.pkg.tar.zst \
+ -C "$calendar_eds_root"
+python3 tools/calendar/probe.py local \
+ --eds-prefix "$calendar_eds_root/usr" --idle-seconds 15
+```
+
+That archive path is machine-specific. `--eds-prefix` accepts the same layout
+from another compatible package. The runner relocates `.pc` directory values
+in a temporary copy and sets a private library search path; it does not edit
+the extracted package or install it. Only the local EDS calendar backend is
+loaded. The Microsoft provider lives in an additional package and is not
+exercised here.
+
+## What each check establishes
+
+`native_probe.c` parses, serializes and reparses an embedded timezone, a
+recurring master, moved/cancelled exceptions and unknown metadata. It expands
+a bounded master range with an exclusion across an Auckland DST change. A
+small synthetic SQLite schema checks rollback and retention of a pending edit
+and base revision through cache replacement and database reopen. It does not
+apply detached exceptions to an agenda, resolve a conflict, recover from power
+loss or send a pending edit to a provider.
+
+`eds_probe.c` creates a local calendar, creates/edits a recurring master and
+moves one occurrence. The runner stops the calendar factory, source registry
+and bus, starts fresh processes, then reads the stored event and exception
+using the original occurrence identity. This establishes orderly restart
+persistence, not recovery from a crash during a write. Its blocking C API
+calls are confined to the disposable CLI; an eventual service bridge still
+needs asynchronous subscriptions and cancellation.
+
+The Linux-only idle observation reports PSS/RSS and per-thread context-switch
+deltas after the client disconnects. Threads entering or leaving the sample
+are counted separately; departed threads' final counters are unavailable.
+This local-only runtime disables backend subprocesses and uses `--keep-running`
+for measurement. It is not the production process layout or a qualified idle
+budget. There is no equivalent native-service measurement because that service
+does not exist yet.
+
+## Isolation and teardown
+
+Each invocation builds into a fresh mode-0700 temporary directory. HOME and
+all XDG paths point inside it. The environment excludes inherited display,
+bus, proxy and credential settings. The EDS run starts its own bus with no
+activation service directories, points the system bus at a nonexistent private
+socket, loads only the local calendar module and uses memory-backed settings.
+No network account is configured, no keyring is activated, and no host EDS or
+compositor service is contacted. This is fixture isolation, not an OS network
+sandbox for arbitrary untrusted code.
+
+Compiler and probe calls have deadlines; owned process groups are terminated
+on timeout or teardown, including children whose parent has already exited.
+The runner removes temporary state after either success or failure. The C
+probes are intended to be run through this wrapper. EDS also checks the private
+directory and bus environment before connecting.
diff --git a/tools/calendar/eds_probe.c b/tools/calendar/eds_probe.c
new file mode 100644
index 0000000..6811cd4
--- /dev/null
+++ b/tools/calendar/eds_probe.c
@@ -0,0 +1,179 @@
+/* Noninstalled Phase 0 probe. Run only through the private-bus harness.
+ * This checks EDS's local store, not OAuth, provider sync or offline remote writes.
+ * Blocking client calls are intentional in this disposable CLI process.
+ */
+#define _POSIX_C_SOURCE 200809L
+#include <libecal/libecal.h>
+#include <libedataserver/libedataserver.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#define SOURCE_UID "rediwm-calendar-phase0-local"
+#define EVENT_UID "rediwm-calendar-phase0-recurring"
+#define ORIGINAL_TIME "20261031T090000Z"
+#define MOVED_TIME "20261031T120000Z"
+
+static const char master_text[] =
+ "BEGIN:VEVENT\r\n"
+ "UID:" EVENT_UID "\r\n"
+ "DTSTAMP:20261001T000000Z\r\n"
+ "DTSTART:20261030T090000Z\r\n"
+ "DTEND:20261030T100000Z\r\n"
+ "RRULE:FREQ=DAILY;COUNT=3\r\n"
+ "SUMMARY:Phase 0 original series\r\n"
+ "END:VEVENT\r\n";
+
+static const char exception_text[] =
+ "BEGIN:VEVENT\r\n"
+ "UID:" EVENT_UID "\r\n"
+ "DTSTAMP:20261001T000000Z\r\n"
+ "RECURRENCE-ID:" ORIGINAL_TIME "\r\n"
+ "DTSTART:" MOVED_TIME "\r\n"
+ "DTEND:20261031T130000Z\r\n"
+ "SUMMARY:Phase 0 moved occurrence\r\n"
+ "END:VEVENT\r\n";
+
+static void fail(const char *stage, GError *error) {
+ /* Errors are from a synthetic local fixture, never provider responses. */
+ fprintf(stderr, "EDS local probe: %s: %s\n", stage,
+ error ? error->message : "check failed");
+ g_clear_error(&error);
+ exit(EXIT_FAILURE);
+}
+
+static void require_private_environment(const char *root) {
+ static const char *names[] = {
+ "HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_RUNTIME_DIR"
+ };
+ struct stat info;
+ size_t length = strlen(root);
+ if (!g_path_is_absolute(root) || length < 2 || root[length - 1] == '/' ||
+ lstat(root, &info) != 0 || !S_ISDIR(info.st_mode) ||
+ info.st_uid != getuid() || (info.st_mode & 077) != 0)
+ fail("private root must be an owned mode-0700 directory", NULL);
+ for (size_t index = 0; index < G_N_ELEMENTS(names); index++) {
+ const char *value = g_getenv(names[index]);
+ if (!value || strncmp(value, root, length) != 0 || value[length] != '/' ||
+ strstr(value + length, "/../") || g_str_has_suffix(value, "/..") ||
+ lstat(value, &info) != 0 || !S_ISDIR(info.st_mode) ||
+ info.st_uid != getuid() || (info.st_mode & 077) != 0)
+ fail("HOME and XDG paths must be private directories beneath root", NULL);
+ }
+ gchar *address = g_strdup_printf("unix:path=%s/bus", root);
+ const char *actual = g_getenv("DBUS_SESSION_BUS_ADDRESS");
+ gboolean valid = actual &&
+ (g_strcmp0(actual, address) == 0 ||
+ (g_str_has_prefix(actual, address) &&
+ g_str_has_prefix(actual + strlen(address), ",guid=") &&
+ !strchr(actual, ';')));
+ g_free(address);
+ if (!valid) fail("session bus must be the harness's private root/bus", NULL);
+}
+
+static ESource *open_source(ESourceRegistry *registry, gboolean writing) {
+ GError *error = NULL;
+ ESource *source = e_source_registry_ref_source(registry, SOURCE_UID);
+ if (!writing) {
+ if (!source) fail("source did not survive service restart", NULL);
+ return source;
+ }
+ if (source) fail("write requires a fresh private store", NULL);
+ source = e_source_new_with_uid(SOURCE_UID, NULL, &error);
+ if (!source) fail("create source", error);
+ e_source_set_display_name(source, "RediWM Phase 0 synthetic local calendar");
+ e_source_set_enabled(source, TRUE);
+ ESourceBackend *backend = E_SOURCE_BACKEND(
+ e_source_get_extension(source, E_SOURCE_EXTENSION_CALENDAR));
+ e_source_backend_set_backend_name(backend, "local");
+ if (!e_source_registry_commit_source_sync(registry, source, NULL, &error))
+ fail("persist source", error);
+ return source;
+}
+
+static void write_events(ECalClient *client) {
+ GError *error = NULL;
+ gchar *uid = NULL;
+ ICalComponent *master = i_cal_component_new_from_string(master_text);
+ if (!master) fail("parse master fixture", NULL);
+ if (!e_cal_client_create_object_sync(client, master, E_CAL_OPERATION_FLAG_NONE,
+ &uid, NULL, &error))
+ fail("create recurring event", error);
+ if (g_strcmp0(uid, EVENT_UID) != 0) fail("local backend changed fixture UID", NULL);
+ g_free(uid);
+ i_cal_component_set_summary(master, "Phase 0 edited series");
+ if (!e_cal_client_modify_object_sync(client, master, E_CAL_OBJ_MOD_ALL,
+ E_CAL_OPERATION_FLAG_NONE, NULL, &error))
+ fail("edit whole series", error);
+ g_object_unref(master);
+ ICalComponent *exception = i_cal_component_new_from_string(exception_text);
+ if (!exception) fail("parse exception fixture", NULL);
+ if (!e_cal_client_modify_object_sync(client, exception, E_CAL_OBJ_MOD_THIS,
+ E_CAL_OPERATION_FLAG_NONE, NULL, &error))
+ fail("move one occurrence", error);
+ g_object_unref(exception);
+}
+
+static void check_time(ICalTime *time, const char *expected) {
+ if (!time) fail("missing occurrence time", NULL);
+ gchar *actual = i_cal_time_as_ical_string(time);
+ gboolean matches = g_strcmp0(actual, expected) == 0;
+ g_free(actual);
+ g_object_unref(time);
+ if (!matches) fail("occurrence time or original identity changed", NULL);
+}
+
+static void read_events(ECalClient *client) {
+ GError *error = NULL;
+ ICalComponent *master = NULL;
+ ICalComponent *exception = NULL;
+ if (!e_cal_client_get_object_sync(client, EVENT_UID, NULL, &master, NULL, &error))
+ fail("read recurring master", error);
+ if (g_strcmp0(i_cal_component_get_summary(master), "Phase 0 edited series") != 0)
+ fail("series edit did not persist", NULL);
+ ICalProperty *rule = i_cal_component_get_first_property(master, I_CAL_RRULE_PROPERTY);
+ if (!rule) fail("recurrence rule missing", NULL);
+ ICalRecurrence *recurrence = i_cal_property_get_rrule(rule);
+ if (!recurrence || i_cal_recurrence_get_count(recurrence) != 3)
+ fail("recurrence count changed", NULL);
+ g_object_unref(recurrence);
+ g_object_unref(rule);
+ g_object_unref(master);
+ if (!e_cal_client_get_object_sync(client, EVENT_UID, ORIGINAL_TIME,
+ &exception, NULL, &error))
+ fail("read moved occurrence by original identity", error);
+ if (g_strcmp0(i_cal_component_get_summary(exception), "Phase 0 moved occurrence") != 0)
+ fail("exception edit did not persist", NULL);
+ check_time(i_cal_component_get_recurrenceid(exception), ORIGINAL_TIME);
+ check_time(i_cal_component_get_dtstart(exception), MOVED_TIME);
+ g_object_unref(exception);
+}
+
+int main(int argc, char **argv) {
+ if (argc != 3 || (strcmp(argv[1], "write") != 0 && strcmp(argv[1], "read") != 0)) {
+ fputs("usage: eds-probe write|read PRIVATE_ROOT\n", stderr);
+ return EXIT_FAILURE;
+ }
+ require_private_environment(argv[2]);
+ gboolean writing = strcmp(argv[1], "write") == 0;
+ GError *error = NULL;
+ ESourceRegistry *registry = e_source_registry_new_sync(NULL, &error);
+ if (!registry) fail("connect private source registry", error);
+ ESource *source = open_source(registry, writing);
+ /* EDS's documented -1 sentinel skips waiting for remote connectivity. */
+ EClient *base = e_cal_client_connect_sync(source, E_CAL_CLIENT_SOURCE_TYPE_EVENTS,
+ G_MAXUINT32, NULL, &error);
+ if (!base) fail("connect local calendar", error);
+ ECalClient *client = E_CAL_CLIENT(base);
+ if (writing) write_events(client);
+ read_events(client);
+ printf("{\"status\":\"pass\",\"scope\":\"eds_local_store\",\"stage\":\"%s\","
+ "\"series_edit\":true,\"moved_occurrence\":true,"
+ "\"provider_qualification\":false}\n", argv[1]);
+ g_object_unref(base);
+ g_object_unref(source);
+ g_object_unref(registry);
+ return EXIT_SUCCESS;
+}
diff --git a/tools/calendar/eds_runtime.py b/tools/calendar/eds_runtime.py
new file mode 100644
index 0000000..feefe41
--- /dev/null
+++ b/tools/calendar/eds_runtime.py
@@ -0,0 +1,198 @@
+"""Private local-only EDS runtime for probe.py; no host service activation."""
+
+from contextlib import contextmanager
+import json
+import os
+from pathlib import Path
+import select
+import shutil
+import signal
+import subprocess
+import time
+from xml.sax.saxutils import escape
+
+
+def location(prefix, relative, alternatives=()):
+ candidates = [prefix / relative] if prefix else [Path("/usr") / relative, *alternatives]
+ for candidate in candidates:
+ if candidate.exists():
+ return candidate
+ raise RuntimeError(f"EDS runtime file missing: {relative}")
+
+
+def configure(root, env, prefix, run):
+ registry = location(prefix, "lib/evolution-source-registry", (
+ Path("/usr/libexec/evolution-source-registry"),))
+ factory = location(prefix, "lib/evolution-calendar-factory", (
+ Path("/usr/libexec/evolution-calendar-factory"),))
+ backend = location(prefix, "lib/evolution-data-server/calendar-backends/libecalbackendfile.so", (
+ Path("/usr/lib64/evolution-data-server/calendar-backends/libecalbackendfile.so"),
+ Path("/usr/lib/x86_64-linux-gnu/evolution-data-server/calendar-backends/libecalbackendfile.so"),))
+ schemas = location(prefix, "share/glib-2.0/schemas")
+ schema_dir = root / "schemas"
+ schema_dir.mkdir(mode=0o700)
+ # Compile EDS schemas alone; no dconf or host settings are used.
+ for path in schemas.glob("*.gschema.xml"):
+ if "evolution" in path.name.lower():
+ shutil.copyfile(path, schema_dir / path.name)
+ run(["glib-compile-schemas", str(schema_dir)], env)
+ local_modules = root / "local-modules"
+ local_modules.mkdir(mode=0o700)
+ (local_modules / backend.name).symlink_to(backend)
+ empty_modules = root / "empty-modules"
+ empty_modules.mkdir(mode=0o700)
+ env = dict(env, EDS_TESTING="1", EDS_REGISTRY_MODULES=str(empty_modules),
+ EDS_CALENDAR_MODULES=str(local_modules), GSETTINGS_SCHEMA_DIR=str(schema_dir))
+ config = root / "bus.conf"
+ config.write_text(f"""<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
+"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
+<busconfig>
+ <type>session</type>
+ <listen>unix:path={escape(str(root / 'bus'))}</listen>
+ <auth>EXTERNAL</auth>
+ <policy context="default">
+ <allow user="{os.getuid()}"/>
+ <allow own="*"/>
+ <allow send_destination="*"/>
+ <allow receive_sender="*"/>
+ </policy>
+</busconfig>
+""")
+ return registry, factory, config, env
+
+
+def stop(process):
+ try:
+ os.killpg(process.pid, signal.SIGTERM)
+ except ProcessLookupError:
+ process.wait(timeout=5)
+ return
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ pass
+ finally:
+ # Descendants may outlive an already-exited parent or ignore SIGTERM.
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait(timeout=5)
+
+
+@contextmanager
+def services(registry, factory, config, root, env, run, stage):
+ processes, logs = {}, []
+ try:
+ commands = (
+ ("bus", ["dbus-daemon", "--nofork", "--print-address=1", f"--config-file={config}"]),
+ ("registry", [str(registry), "--disable-migration"]),
+ ("calendar", [str(factory), "--keep-running", "--backend-per-process=0"]),
+ )
+ for name, argv in commands:
+ log = (root / f"{stage}-{name}.log").open("w+")
+ logs.append(log)
+ processes[name] = subprocess.Popen(argv, env=env,
+ stdout=subprocess.PIPE if name == "bus" else log,
+ stderr=log, text=True, start_new_session=True)
+ if name == "bus":
+ pipe = processes[name].stdout
+ if not select.select([pipe], [], [], 10)[0]:
+ raise RuntimeError("private D-Bus readiness timed out")
+ address = pipe.readline().strip()
+ pipe.close()
+ if not address.startswith(env["DBUS_SESSION_BUS_ADDRESS"] + ",guid="):
+ raise RuntimeError("private D-Bus failed to report its address")
+ else:
+ bus_name = "org.gnome.evolution.dataserver." + (
+ "Sources5" if name == "registry" else "Calendar8")
+ run(["gdbus", "wait", "--address", env["DBUS_SESSION_BUS_ADDRESS"],
+ "--timeout", "10", bus_name], env, 15)
+ yield processes
+ except Exception as error:
+ details = []
+ for log in logs:
+ log.flush()
+ log.seek(0)
+ details.append(f"{Path(log.name).name}: {log.read()[-2000:]}")
+ raise RuntimeError(f"{error}\n" + "\n".join(details)) from error
+ finally:
+ try:
+ errors = []
+ for process in reversed(list(processes.values())):
+ try:
+ stop(process)
+ except (OSError, subprocess.TimeoutExpired) as error:
+ errors.append(str(error))
+ if errors:
+ raise RuntimeError("private service cleanup failed: " + "; ".join(errors))
+ finally:
+ for log in logs:
+ log.close()
+
+
+def stats(processes):
+ result = {}
+ for name, process in processes.items():
+ if process.poll() is not None:
+ raise RuntimeError(f"{name} exited during idle measurement")
+ base = Path(f"/proc/{process.pid}")
+ if not base.exists():
+ return None # Linux-only optional observation.
+ memory = {}
+ try:
+ for line in (base / "smaps_rollup").read_text().splitlines():
+ key, _, value = line.partition(":")
+ if key in ("Rss", "Pss", "Private_Clean", "Private_Dirty"):
+ memory[key + "_kib"] = int(value.split()[0])
+ except (FileNotFoundError, PermissionError):
+ pass
+ threads = {}
+ for task in (base / "task").iterdir():
+ try:
+ status = dict(line.split(":", 1) for line in (task / "status").read_text().splitlines())
+ threads[task.name] = {
+ "name": status["Name"].strip(),
+ "voluntary": int(status["voluntary_ctxt_switches"]),
+ "involuntary": int(status["nonvoluntary_ctxt_switches"]),
+ }
+ except FileNotFoundError:
+ continue
+ result[name] = {"memory": memory, "threads": threads}
+ return result
+
+
+def idle_sample(processes, seconds):
+ before = stats(processes)
+ start = time.monotonic()
+ time.sleep(seconds)
+ after = stats(processes)
+ if before is None or after is None:
+ return {"status": "unavailable", "reason": "requires Linux procfs"}
+ result = {"seconds": round(time.monotonic() - start, 3), "processes": {}}
+ for name, current in after.items():
+ previous = before[name]["threads"]
+ threads = []
+ for tid, values in current["threads"].items():
+ if tid in previous:
+ threads.append({"name": values["name"],
+ "voluntary_delta": values["voluntary"] - previous[tid]["voluntary"],
+ "involuntary_delta": values["involuntary"] - previous[tid]["involuntary"]})
+ result["processes"][name] = {"memory": current["memory"], "threads": threads,
+ "new_threads": len(current["threads"].keys() - previous.keys()),
+ "exited_threads": len(previous.keys() - current["threads"].keys())}
+ return result
+
+
+def probe(executable, root, env, prefix, idle_seconds, run):
+ registry, factory, config, env = configure(root, env, prefix, run)
+ with services(registry, factory, config, root, env, run, "write"):
+ written = json.loads(run([str(executable), "write", str(root)], env))
+ # A fresh private bus and fresh EDS processes must read the same on-disk state.
+ with services(registry, factory, config, root, env, run, "read") as processes:
+ restored = json.loads(run([str(executable), "read", str(root)], env))
+ time.sleep(1) # Allow client-disconnect work to settle before measuring.
+ idle = idle_sample(processes, idle_seconds)
+ return {"status": "pass", "write": written, "after_service_restart": restored,
+ "runtime": "local module only; backend-per-process=0; no activation services",
+ "idle": idle, "provider_qualification": False}
diff --git a/tools/calendar/native_probe.c b/tools/calendar/native_probe.c
new file mode 100644
index 0000000..f35d44b
--- /dev/null
+++ b/tools/calendar/native_probe.c
@@ -0,0 +1,244 @@
+/* Noninstalled Phase 0 dependency probe, not a calendar backend or sync engine.
+ * Run only against a fresh private database owned by the qualification harness.
+ * Detached exceptions are preserved and inspected, not expanded/merged here.
+ */
+#include <libical/ical.h>
+#include <sqlite3.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static const char fixture[] =
+ "BEGIN:VCALENDAR\r\n"
+ "VERSION:2.0\r\n"
+ "PRODID:-//RediWM//Phase 0 probe//EN\r\n"
+ "BEGIN:VTIMEZONE\r\n"
+ "TZID:Pacific/Auckland\r\n"
+ "BEGIN:STANDARD\r\n"
+ "DTSTART:20260405T030000\r\n"
+ "TZOFFSETFROM:+1300\r\n"
+ "TZOFFSETTO:+1200\r\n"
+ "RRULE:FREQ=YEARLY;BYMONTH=4;BYDAY=1SU\r\n"
+ "END:STANDARD\r\n"
+ "BEGIN:DAYLIGHT\r\n"
+ "DTSTART:20260927T020000\r\n"
+ "TZOFFSETFROM:+1200\r\n"
+ "TZOFFSETTO:+1300\r\n"
+ "RRULE:FREQ=YEARLY;BYMONTH=9;BYDAY=-1SU\r\n"
+ "END:DAYLIGHT\r\n"
+ "END:VTIMEZONE\r\n"
+ "BEGIN:VEVENT\r\n"
+ "UID:phase0-series\r\n"
+ "DTSTAMP:20261031T000000Z\r\n"
+ "DTSTART;TZID=Pacific/Auckland:20260926T090000\r\n"
+ "DTEND;TZID=Pacific/Auckland:20260926T100000\r\n"
+ "RRULE:FREQ=DAILY;COUNT=5\r\n"
+ "EXDATE;TZID=Pacific/Auckland:20260930T090000\r\n"
+ "SUMMARY:Dependency probe\r\n"
+ "X-EXTERNAL-STATE:preserve-me\r\n"
+ "END:VEVENT\r\n"
+ "BEGIN:VEVENT\r\n"
+ "UID:phase0-series\r\n"
+ "DTSTAMP:20261031T000000Z\r\n"
+ "RECURRENCE-ID;TZID=Pacific/Auckland:20260928T090000\r\n"
+ "DTSTART;TZID=Pacific/Auckland:20260928T110000\r\n"
+ "DTEND;TZID=Pacific/Auckland:20260928T120000\r\n"
+ "SUMMARY:Moved occurrence\r\n"
+ "END:VEVENT\r\n"
+ "BEGIN:VEVENT\r\n"
+ "UID:phase0-series\r\n"
+ "DTSTAMP:20261031T000000Z\r\n"
+ "RECURRENCE-ID;TZID=Pacific/Auckland:20260929T090000\r\n"
+ "DTSTART;TZID=Pacific/Auckland:20260929T090000\r\n"
+ "DTEND;TZID=Pacific/Auckland:20260929T100000\r\n"
+ "STATUS:CANCELLED\r\n"
+ "END:VEVENT\r\n"
+ "END:VCALENDAR\r\n";
+
+static void require(bool condition, const char *stage)
+{
+ if (!condition) {
+ fprintf(stderr, "native calendar probe failed: %s\n", stage);
+ exit(EXIT_FAILURE);
+ }
+}
+
+static bool property_equals(icalcomponent *event, icalproperty_kind kind,
+ const char *value)
+{
+ icalproperty *property = icalcomponent_get_first_property(event, kind);
+ const char *actual = property ? icalproperty_get_value_as_string(property) : NULL;
+ return actual && strcmp(actual, value) == 0;
+}
+
+static void check_zone(icalcomponent *event, icalproperty_kind kind)
+{
+ icalproperty *property = icalcomponent_get_first_property(event, kind);
+ require(property != NULL, "timezone property exists");
+ icalparameter *parameter = icalproperty_get_first_parameter(property, ICAL_TZID_PARAMETER);
+ const char *tzid = parameter ? icalparameter_get_tzid(parameter) : NULL;
+ require(tzid && strcmp(tzid, "Pacific/Auckland") == 0, "timezone parameter preserved");
+}
+
+static icalcomponent *check_components(icalcomponent *calendar)
+{
+ require(calendar && icalcomponent_isa(calendar) == ICAL_VCALENDAR_COMPONENT,
+ "parse VCALENDAR");
+ require(icalcomponent_count_errors(calendar) == 0, "no parse errors");
+ require(icalcomponent_get_timezone(calendar, "Pacific/Auckland") != NULL,
+ "embedded timezone preserved");
+ icalcomponent *master = NULL;
+ unsigned moved = 0, cancelled = 0, count = 0;
+ for (icalcomponent *event = icalcomponent_get_first_component(calendar, ICAL_VEVENT_COMPONENT);
+ event; event = icalcomponent_get_next_component(calendar, ICAL_VEVENT_COMPONENT)) {
+ require(++count <= 3, "bounded component count");
+ const char *uid = icalcomponent_get_uid(event);
+ require(uid && strcmp(uid, "phase0-series") == 0, "series identity preserved");
+ check_zone(event, ICAL_DTSTART_PROPERTY);
+ if (icaltime_is_null_time(icalcomponent_get_recurrenceid(event))) {
+ require(!master, "one series master");
+ master = event;
+ require(property_equals(event, ICAL_RRULE_PROPERTY, "FREQ=DAILY;COUNT=5"),
+ "recurrence rule preserved");
+ require(property_equals(event, ICAL_EXDATE_PROPERTY, "20260930T090000"),
+ "excluded occurrence preserved");
+ require(property_equals(event, ICAL_X_PROPERTY, "preserve-me"),
+ "unrecognized metadata preserved");
+ } else {
+ check_zone(event, ICAL_RECURRENCEID_PROPERTY);
+ if (icalcomponent_get_status(event) == ICAL_STATUS_CANCELLED) {
+ require(property_equals(event, ICAL_RECURRENCEID_PROPERTY, "20260929T090000"),
+ "cancelled occurrence retains original identity");
+ cancelled++;
+ } else {
+ require(property_equals(event, ICAL_RECURRENCEID_PROPERTY, "20260928T090000"),
+ "moved occurrence retains original identity");
+ require(property_equals(event, ICAL_DTSTART_PROPERTY, "20260928T110000"),
+ "moved start remains separate from identity");
+ moved++;
+ }
+ }
+ }
+ require(count == 3 && master && moved == 1 && cancelled == 1, "exception components preserved");
+ return master;
+}
+
+struct expansion {
+ icaltimezone *zone;
+ unsigned count;
+ icaltime_t previous;
+};
+
+static void occurrence(icalcomponent *event, const struct icaltime_span *span, void *data)
+{
+ (void)event;
+ struct expansion *result = data;
+ require(result->count < 4, "bounded recurrence output");
+ struct icaltimetype local = icaltime_from_timet_with_zone(span->start, false, result->zone);
+ require(local.year == 2026 && local.month == 9 && local.day == 26 + (int)result->count &&
+ local.hour == 9 && local.minute == 0, "wall time preserved across DST");
+ require(span->end - span->start == 3600, "occurrence duration preserved");
+ if (result->count)
+ require(span->start - result->previous == (result->count == 1 ? 23 : 24) * 3600,
+ "UTC spacing changes across DST");
+ result->previous = span->start;
+ result->count++;
+}
+
+static void check_expansion(icalcomponent *calendar)
+{
+ icalcomponent *master = check_components(calendar);
+ struct expansion result = { .zone = icalcomponent_get_timezone(calendar, "Pacific/Auckland") };
+ icalcomponent_foreach_recurrence(master, icaltime_from_string("20260925T000000Z"),
+ icaltime_from_string("20261001T000000Z"), occurrence, &result);
+ require(result.count == 4, "bounded master expansion honors EXDATE");
+}
+
+static void sql(sqlite3 *db, const char *statement)
+{
+ require(sqlite3_exec(db, statement, NULL, NULL, NULL) == SQLITE_OK, "SQLite statement");
+}
+
+static void insert_remote(sqlite3 *db, const char *calendar, int revision)
+{
+ sqlite3_stmt *statement = NULL;
+ require(sqlite3_prepare_v2(db, "INSERT INTO remote VALUES('phase0-series',?1,?2)",
+ -1, &statement, NULL) == SQLITE_OK, "prepare cache insert");
+ require(sqlite3_bind_int(statement, 1, revision) == SQLITE_OK &&
+ sqlite3_bind_text(statement, 2, calendar, -1, SQLITE_TRANSIENT) == SQLITE_OK,
+ "bind cache insert");
+ require(sqlite3_step(statement) == SQLITE_DONE, "insert cache record");
+ require(sqlite3_finalize(statement) == SQLITE_OK, "finalize cache insert");
+}
+
+static int scalar(sqlite3 *db, const char *query)
+{
+ sqlite3_stmt *statement = NULL;
+ require(sqlite3_prepare_v2(db, query, -1, &statement, NULL) == SQLITE_OK, "prepare scalar query");
+ require(sqlite3_step(statement) == SQLITE_ROW, "read scalar row");
+ int result = sqlite3_column_int(statement, 0);
+ require(sqlite3_step(statement) == SQLITE_DONE, "only one scalar row");
+ require(sqlite3_finalize(statement) == SQLITE_OK, "finalize scalar query");
+ return result;
+}
+
+static void check_store(const char *path, const char *calendar)
+{
+ sqlite3 *db = NULL;
+ require(sqlite3_open_v2(path, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL) == SQLITE_OK,
+ "open private database");
+ /* Refuse a pre-existing schema before any PRAGMA or write. */
+ require(scalar(db, "SELECT count(*) FROM sqlite_master") == 0, "database must be fresh");
+ sql(db, "PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; BEGIN IMMEDIATE;"
+ "CREATE TABLE remote(uid TEXT PRIMARY KEY,revision INTEGER NOT NULL,ical TEXT NOT NULL);"
+ "CREATE TABLE pending(id TEXT PRIMARY KEY,base_revision INTEGER NOT NULL,edit TEXT NOT NULL);");
+ insert_remote(db, calendar, 1);
+ sql(db, "INSERT INTO pending VALUES('local-1',1,'offline title edit'); COMMIT;"
+ "BEGIN IMMEDIATE; UPDATE remote SET revision=99; DELETE FROM pending; ROLLBACK;");
+ require(scalar(db, "SELECT revision FROM remote") == 1 &&
+ scalar(db, "SELECT count(*) FROM pending") == 1, "rollback preserves cache and pending edit");
+ sql(db, "BEGIN IMMEDIATE; DELETE FROM remote;");
+ insert_remote(db, calendar, 2);
+ sql(db, "COMMIT;");
+ require(sqlite3_close(db) == SQLITE_OK, "close database");
+ require(sqlite3_open_v2(path, &db, SQLITE_OPEN_READWRITE, NULL) == SQLITE_OK, "reopen database");
+ require(scalar(db, "SELECT revision FROM remote") == 2 &&
+ scalar(db, "SELECT count(*) FROM pending WHERE id='local-1' AND base_revision=1 "
+ "AND edit='offline title edit'") == 1,
+ "pending edit and base revision survive cache replacement and reopen");
+ sqlite3_stmt *statement = NULL;
+ require(sqlite3_prepare_v2(db, "SELECT ical FROM remote", -1, &statement, NULL) == SQLITE_OK &&
+ sqlite3_step(statement) == SQLITE_ROW, "load durable calendar");
+ const char *stored = (const char *)sqlite3_column_text(statement, 0);
+ require(stored && strcmp(stored, calendar) == 0, "calendar bytes survive reopen");
+ icalcomponent *restored = icalparser_parse_string(stored);
+ check_expansion(restored);
+ icalcomponent_free(restored);
+ require(sqlite3_finalize(statement) == SQLITE_OK, "finalize calendar load");
+ require(sqlite3_close(db) == SQLITE_OK, "close reopened database");
+}
+
+int main(int argc, char **argv)
+{
+ if (argc != 2) {
+ fprintf(stderr, "usage: native-probe FRESH_PRIVATE_DATABASE\n");
+ return EXIT_FAILURE;
+ }
+ icalcomponent *original = icalparser_parse_string(fixture);
+ check_expansion(original);
+ char *rendered = icalcomponent_as_ical_string_r(original);
+ require(rendered != NULL, "serialize calendar");
+ icalcomponent *roundtrip = icalparser_parse_string(rendered);
+ check_expansion(roundtrip);
+ check_store(argv[1], rendered);
+ icalcomponent_free(roundtrip);
+ icalmemory_free_buffer(rendered);
+ icalcomponent_free(original);
+ icaltimezone_free_builtin_timezones();
+ puts("{\"status\":\"pass\",\"ical_roundtrip\":true,\"dst_master_expansion\":true,"
+ "\"exception_identity_preservation\":true,\"sqlite_rollback\":true,"
+ "\"pending_survives_cache_refresh_and_reopen\":true,"
+ "\"exception_overlay_applied\":false,\"provider_qualification\":false}");
+ return EXIT_SUCCESS;
+}
diff --git a/tools/calendar/probe.py b/tools/calendar/probe.py
new file mode 100644
index 0000000..11b3d0e
--- /dev/null
+++ b/tools/calendar/probe.py
@@ -0,0 +1,162 @@
+#!/usr/bin/env python3
+"""Noninstalled Calendar Phase 0 probes; never connects to provider accounts."""
+
+import argparse
+import json
+import os
+from pathlib import Path
+import shlex
+import shutil
+import signal
+import subprocess
+import tempfile
+
+HERE = Path(__file__).resolve().parent
+PACKAGES = {
+ "native": ("sqlite3", "libical", "libcurl"),
+ "eds": ("libecal-2.0", "libedataserver-1.2"),
+ "keyring": ("libsecret-1",),
+}
+
+
+def run(argv, env, timeout=30):
+ """Bound commands and kill their children as well if a compiler/probe stalls."""
+ process = subprocess.Popen(argv, env=env, text=True, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, start_new_session=True)
+ try:
+ stdout, stderr = process.communicate(timeout=timeout)
+ except BaseException:
+ # A compiler's parent may have exited while a child still owns its pipes.
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.communicate(timeout=5)
+ raise
+ if process.returncode:
+ raise RuntimeError(f"{Path(argv[0]).name} exited {process.returncode}: "
+ f"{stderr[-4000:] or stdout[-4000:]}")
+ return stdout
+
+
+def private_environment(root, prefix):
+ # An allowlist keeps inherited display, bus, proxy, credential and EDS settings out.
+ env = {"PATH": os.environ.get("PATH", os.defpath), "LC_ALL": "C.UTF-8", "TZ": "UTC"}
+ for key, directory in (("HOME", "home"), ("XDG_CONFIG_HOME", "config"),
+ ("XDG_DATA_HOME", "data"), ("XDG_STATE_HOME", "state"),
+ ("XDG_CACHE_HOME", "cache"), ("XDG_RUNTIME_DIR", "runtime"),
+ ("TMPDIR", "tmp")):
+ path = root / directory
+ path.mkdir(mode=0o700)
+ env[key] = str(path)
+ env.update(DBUS_SESSION_BUS_ADDRESS=f"unix:path={root}/bus",
+ DBUS_SYSTEM_BUS_ADDRESS=f"unix:path={root}/no-system-bus",
+ XDG_CONFIG_DIRS=str(root / "config"), XDG_DATA_DIRS=str(root / "data"),
+ GSETTINGS_BACKEND="memory", GIO_USE_NETWORK_MONITOR="base")
+ if prefix:
+ # Relocate only the supplied EDS .pc files, never dependency .pc files.
+ pkgdir = root / "pkgconfig"
+ pkgdir.mkdir(mode=0o700)
+ for source in (prefix / "lib/pkgconfig").glob("*.pc"):
+ lines = []
+ for line in source.read_text().splitlines():
+ key, sep, value = line.partition("=")
+ if sep and (value == "/usr" or value.startswith("/usr/")):
+ line = f"{key}={prefix}{value[4:]}"
+ lines.append(line)
+ (pkgdir / source.name).write_text("\n".join(lines) + "\n")
+ env["PKG_CONFIG_PATH"] = str(pkgdir)
+ env["LD_LIBRARY_PATH"] = f"{prefix}/lib:{prefix}/lib/evolution-data-server"
+ return env
+
+
+def inventory(env, prefix):
+ packages = {}
+ for name in dict.fromkeys(p for group in PACKAGES.values() for p in group):
+ try:
+ packages[name] = {"status": "available", "version": run(
+ ["pkg-config", "--modversion", name], env).strip()}
+ except (OSError, RuntimeError) as error:
+ packages[name] = {"status": "unavailable", "detail": str(error)}
+ modules = []
+ module_roots = [prefix / "lib/evolution-data-server"] if prefix else [
+ Path("/usr/lib/evolution-data-server"), Path("/usr/lib64/evolution-data-server"),
+ Path("/usr/lib/x86_64-linux-gnu/evolution-data-server")]
+ for directory in module_roots:
+ if directory.exists():
+ modules.extend(path.name for path in directory.rglob("*.so")
+ if "m365" in path.name or "caldav" in path.name)
+ return {"packages": packages, "provider_modules": sorted(set(modules)),
+ "tools": {name: shutil.which(name, path=env["PATH"]) is not None
+ for name in ("cc", "pkg-config", "dbus-daemon", "gdbus",
+ "glib-compile-schemas")},
+ "keyring_access": "not_tested", "provider_access": "not_tested"}
+
+
+def compile_probe(name, packages, root, env, prefix):
+ flags = shlex.split(run(["pkg-config", "--cflags", "--libs", *packages], env))
+ executable = root / f"{name}-probe"
+ extra = []
+ if prefix:
+ extra = [f"-Wl,-rpath-link,{prefix}/lib",
+ f"-Wl,-rpath-link,{prefix}/lib/evolution-data-server"]
+ run(["cc", "-std=c11", "-Wall", "-Wextra", "-Werror", "-g", "-O1",
+ str(HERE / f"{name}_probe.c"), "-o", str(executable), *extra, *flags], env, 60)
+ return executable
+
+
+def local_probe(name, root, env, prefix, idle_seconds, available):
+ needed = PACKAGES[name][:2]
+ missing = [p for p in needed if available["packages"][p]["status"] != "available"]
+ if missing:
+ return {"status": "unavailable", "missing": missing}
+ try:
+ executable = compile_probe(name, needed, root, env, prefix)
+ if name == "native":
+ return json.loads(run([str(executable), str(root / "native.sqlite")], env))
+ from eds_runtime import probe
+ return probe(executable, root, env, prefix, idle_seconds, run)
+ except (OSError, RuntimeError, ValueError, subprocess.TimeoutExpired) as error:
+ return {"status": "fail", "detail": str(error)}
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("command", choices=("inventory", "local"))
+ parser.add_argument("--backend", choices=("native", "eds", "all"), default="all")
+ parser.add_argument("--eds-prefix", type=Path,
+ help="optional extracted EDS /usr directory; no packages are installed")
+ parser.add_argument("--idle-seconds", type=float, default=3,
+ help="EDS per-thread context-switch sample, 1–30 seconds (default 3)")
+ parser.add_argument("--output", type=Path, help="write a new private JSON report (never overwrite)")
+ args = parser.parse_args()
+ if not 1 <= args.idle_seconds <= 30:
+ parser.error("--idle-seconds must be between 1 and 30")
+ prefix = args.eds_prefix.resolve() if args.eds_prefix else None
+ if prefix and not (prefix / "lib/pkgconfig/libecal-2.0.pc").is_file():
+ parser.error("--eds-prefix must contain lib/pkgconfig/libecal-2.0.pc")
+ if args.output and args.output.exists():
+ parser.error("--output already exists; choose a new report path")
+ os.umask(0o077)
+ with tempfile.TemporaryDirectory(prefix="rediwm-calendar-phase0-") as directory:
+ root = Path(directory)
+ env = private_environment(root, prefix)
+ report = {"schema_version": 1, "scope": "local_dependency_prototype",
+ "backend_decision": "pending", "phase0_complete": False,
+ "inventory": inventory(env, prefix)}
+ if args.command == "local":
+ selected = ("native", "eds") if args.backend == "all" else (args.backend,)
+ report["probes"] = {name: local_probe(name, root, env, prefix,
+ args.idle_seconds, report["inventory"])
+ for name in selected}
+ output = json.dumps(report, indent=2) + "\n"
+ if args.output:
+ with args.output.open("x") as destination:
+ destination.write(output)
+ print(output, end="")
+ statuses = [p["status"] for p in report.get("probes", {}).values()]
+ return 1 if "fail" in statuses else 2 if "unavailable" in statuses else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())