Files

254 lines
30 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Dashboard-backed extension project sync
This chapter defines the standard persistence contract for extension-owned
projects that must be visible to multiple users or devices through a dashboard.
ISA Quote is the reference implementation for dashboard-backed file transport.
The word **sync** is used carefully here. A file can be dashboard-backed without
being opted into the host's offline file-sync queue.
## Dashboard web UI
The persistence, cache, queue, and reconciliation descriptions in this chapter distinguish the native host from the dashboard web UI. On web, every filesystem read policy—including `cache-only`—reads authoritative dashboard state, and `filesystem_query_index` queries current authorized dashboard inventory. Network failures remain unavailable or errors. Web inventory returns `source: "dashboard"`, `snapshotComplete: true` only on success, and `reconciliationRevision: 0` because there is no local reconciliation.
Web writes apply immediately even with `metadata.syncable = "true"` or the atomic JSON `syncable` creation hint. They preserve dashboard sync metadata for native clients and return no browser pending upload or journal. Extensions continue polling for changes from other clients. Web creates no file-content cache, offline queue, RIBLT worker, or OPFS storage. Portable upload sources are `text` and `bytesBase64`; `filePath` remains native-only.
The shared workspace pickers can grant read or read-write access outside the extension root. The browser host remembers only versioned grant settings per origin, account, workspace, group, extension, and verified package; the server validates restored IDs, paths, ancestry, group links, and permissions before use. Revocation clears live and remembered grants across tabs. Grants work for the current launch group and cannot recursively delete their own root.
## 20.1 Persistence modes
Extensions must distinguish these persistence modes:
| Mode | API | Shared through dashboard | Works offline after provisioning |
| --- | --- | --- | --- |
| Device-local state | `localstorage_*` with omitted or false `sync` | No | Yes |
| Private synced settings | `localstorage_*` with `sync: true` | Yes, per authenticated user/workspace/group/extension | Confirmed cached reads only |
| Dashboard-backed file | `filesystem_*` without `metadata.syncable` | Yes, immediately after a successful request | No |
| Host-syncable file | `filesystem_*` with exact `metadata.syncable = "true"` | Yes, after host reconciliation | Native host only; browser writes remain online |
Browser hosts advertise `filesystem.persistence.mode = "dashboard-confirmed"` and `offlineWrites = false`. A successful browser mutation means dashboard acceptance, even when the file is marked syncable for native interoperability. Browser `atomic_json_apply.syncable` is a server-side creation hint only and never enables a local operation journal. Browser account/extension KV can hold recovery drafts, but a failed or disconnected shared save must remain a visible failed/unconfirmed operation. Upload/delete/atomic-write availability must come from the current gateway command list; implementation and live-verification status are tracked in the [cloud write plan](../../../plans/cloud-extension-write-support.md).
Dashboard-backed project state uses dashboard-backed files by default. It is the
portable baseline because it uses the ordinary authenticated dashboard file
API and does not depend on the optional `workspace-file-riblt-v1` protocol.
Use host-syncable files only when offline editing is an explicit product
requirement. A locally accepted syncable write is durable on that device, but
is not confirmation that the dashboard or another user has received it.
Extensions must not build another offline queue on top of the host queue.
Atomic object-key updates use `atomic_json_get` and `atomic_json_apply` against the same ordinary canonical workspace files and permissions. `atomic_json_apply.syncable` is an optional boolean creation hint: exact `true` makes a missing file host-syncable, while omission or `false` creates it dashboard-first; it never changes an existing file's persisted mode. All valid JSON roots are accepted, although upsert and remove retain their documented object-key semantics. A syncable get overlays durable unacknowledged operations on the strictly committed RIBLT generation; a non-syncable get reads the dashboard. Callers must preserve explicit absent, unavailable, malformed, and permission-error outcomes instead of treating each as an empty object.
An acknowledged atomic batch is removed from the local journal immediately. The ordinary RIBLT cache can therefore lag the accepted dashboard value until reconciliation, and a read in that window can return the older committed generation or unavailable. `filesystem-index-changed` is the single scoped wake-up event for both pending journal and reconciled file changes. Atomic operations add no tombstone: delete removes the ordinary file, a later operation recreates an absent path from `{}`, and dashboard mutations and whole-file replacements take effect in arrival order.
`localstorage_*`, including synced private settings, is never the canonical source for shared project data. It may hold
preferences, recovery drafts, conflict sidecars, and resumable migration
journals.
## 20.2 ISA project storage and grants
Dashboard-backed projects use real writable `<name>.isap` folders under a group’s shared Projects container. `project.json` is the version 1 basic metadata manifest; `extensions/<extension-id>/` organizes extension data and `assets/` contains media. Namespace names are not permission boundaries: a project read-write grant covers supported data throughout the selected project. Preserve unknown files and extension data.
`projects_list` returns currently available project metadata and canonical folder identities. `projects_create` requires a stable `operationId`, creates the manifest and folder atomically, and grants the creating extension access. Extensions with `projects_open_listed`, `projects_read` and `filesystem_read` permissions can obtain a folder grant directly by resolving an active project ID in the launch group. Remembered grants are bound to account, workspace, immutable launch group, extension package and folder, and are revalidated on use. `projects_set_group_link` changes explicit group availability with current management authorization in both groups; it never copies the project.
The Projects container itself has no inheritable group folder link. Each project has direct group links, allowing another group to use the same persisted folder and KV identities. Unlinking one group preserves the project and other links. The server-owned `isa_project` row identifies the canonical project independently of mutable project files; editing or importing `project.json` cannot create access or publishing authority. Identity-only registry data requires explicit manual cutover rather than automatic migration. New hosts require `isa-project-folders-v1` and do not treat the old registry capability as writable storage.
Project files use dashboard-confirmed persistence by default. KV stores retain their separate syncable selective-cache/outbox behavior: a validated project parent does not have to enable whole-folder filesystem sync for a KV store to use `syncable: true`. Canonical project stores have no extension owner, and checkpoint authority follows the workspace/project and canonical artifact configuration rather than the original opening extension, user or group.
Extension conversion and the standalone shared library’s complete transfer/screens remain release integration requirements. Group supplier catalogs and explicitly group-scoped resources remain outside project namespaces; per-project data belongs inside the selected `.isap`.
### Project start screen
A project-based extension opens on the active group's project overview. ISA Match is the layout reference. Below the extension title and summary counts, put recent activity in the left column and **Projects** (**Projecten**) in the larger right column. Place **+ Create project** (**+ Project maken**) at the top right of the Projects panel, with search, sort and the project rows below. The button opens the setup form where the user enters the project name. On narrow screens, stack Projects above recent activity. Choose fields that help with this extension’s work, such as a planning deadline in ISA Projects or a quote deadline in ISA Match. [Shared UI styling](14-strict-styling-requirements.md)
Use the shared `@isa-warden/isa-project-format` overview when adding a project extension. Pass the host’s `projects.commands` to `createProjectClient` as `projectCommands`. Mount `ProjectWorkspace` with `extensionName`, the host locale and that client. A custom home can use the same `client.list()` and `client.openListed(row)` API. Keep earlier private records accessible through a separate history view when introducing shared storage. ISA Host Test Center uses this approach for private rounds, and writes new rounds only inside the selected project. Workspace-wide reference tools such as ISA Prijzenregister can open their register directly.
On launch, call `projects_list` with `{}` and render every returned active project, including projects created by another extension that this extension has never opened. Use the returned project ID to join any known extension details and to identify each row. Personal recents may provide shortcuts. If the extension offers an archive view, load it separately with `includeArchived: true` and filter on `archived`.
Refresh the inventory when the overview regains focus. Show the empty state after a successful empty response. If a refresh fails, show the error and retain the last successful list for that launch group.
Selecting a row opens that project. Invoke `projects_open_listed` with its stable `projectId` and use the folder reference returned by the host. On older hosts, reopen the selected folder using its existing grant. If access is unavailable, show the access error on the overview. Read the extension’s saved record after the host grants access.
| Result of reading the extension record | What the user sees |
| --- | --- |
| A valid record exists | Open the saved workspace for that project. |
| The dashboard confirms the record is absent and the user can write | Create the extension’s initial data in the selected folder and open its workspace immediately. Use the shared project name wherever a name is required. |
| The record is absent and access is read-only | Show the empty workspace in read-only mode or explain that initialization requires write access. |
| The read failed or returned invalid or uncertain data | Show the problem and allow a retry. Preserve the existing project contents. |
Use `projects_create` when the user explicitly creates a shared project, reusing the same `operationId` on retry. On first open of an existing `.isap`, initialize just the data owned by the opening extension under the original project identity. Use `session.ensureExtensionJson(relativePath, makeDefault)` for a canonical JSON record. For collections, use an empty directory or store when zero items is valid. If a first item is required, use a stable ID and a create-only write after confirming the collection is empty. Concurrent and interrupted opens must reuse the saved data. Collect optional details and source uploads inside the open workspace.
**Verify with two extensions in the same group.** Create a project in A, then open it from B with empty recents. Confirm B opens its initialized workspace on the first click. Reopen in B and verify that its saved record is reused and A’s data is intact. Check simultaneous first opens, a read-only grant and a failed dashboard read. Both extensions should list one shared project with the original ID. An unlinked group must have no access.
### Share project actions with ISA Projects
Publish workflow steps and task handoffs with `publishProjectActions(session, {extensionId, extensionName, sourceRevision, actions})` from `@isa-warden/isa-project-format` 1.2 or later. The provider writes one versioned document at `extensions/<manifest-id>/actions/v1.json` inside the open project. The helper captures the workspace and portable project identity, validates the actions and writes conditionally. Use a monotonically increasing revision of the confirmed source data and a stable key for each action. Reopening an existing project should publish its current data.
Each action carries `key`, `kind`, and `title`. A linked action adds `openCount` and `unit`. Publish zero to finish existing work and a positive count to reopen it. ISA Match uses one action per workflow step. A handoff represents one accepted commitment that Projects owns after import. Both kinds support plain-text `detail`, localized `translations`, and an optional semantic `route` for opening the source view. Projects updates the same board task across refreshes and preserves the team's scheduling and comments.
Consumers call `readProjectActions(session)`. Process valid sources independently, retain the last usable tasks on missing or unreadable data, and use `projectActionText(action, locale)` for display. Source identity consists of workspace, manifest project ID, provider manifest ID and action key. Groups authorized on the same project see the same actions. The host checks each extension's project grant when opening a source route.
## 20.3 Capability and root discovery
Read `get_app_info().projects.commands` for the captured launch. Request `projects_read` to list the group's projects and `projects_write` for project creation or lifecycle actions. Check each command before enabling its action. Request the filesystem or KV permissions needed to read and save this extension’s project data.
Use the project path returned by the host after opening or creating the shared project. For extension-owned group data, `filesystem_ensure_group_folder` returns the current extension’s group root. For datasets shared across extensions in an ordinary workspace folder, use the same authorised folder and dataset identity in every viewer.
### Dedicated viewers for shared datasets
Use the workspace folder `/shared` as the default location for cross-extension datasets. The dashboard provisions it during S3 setup. On an older S3 workspace, a storage-enabled group's host picker can create the missing folder on first use. To bind a viewer, call `open_workspace_folder({ accessPolicy: 'read-only' })`, select `/shared`, and save the returned folder ID and path for this workspace and group. An editor requests editable access. On subsequent launches, open the saved dataset directly while the grant is valid. Keep an existing register's configured folder when upgrading.
One extension can specialise in suppliers and another in the price book. Other extensions, including ISA Match, can display those same sources through their own host access. A dedicated viewer opens its dataset directly when its configured folder is accessible. Keep the format independent of the viewer ID. Loading a viewer reads the canonical source without copying it or initialising a fresh store. Report denied access or a missing source separately from an empty dataset.
Use `createSharedFolderReader` from `@isa-warden/isa-project-format/shared-folder` for relative file, JSON and consistent KV reads. ISA Match’s shared register identifies suppliers in `isa-match-suppliers.json`. Its register ID selects `isa-match-catalog-<id>.kv` for detailed supplier data and `isa-match-prices-<id>.kv` for its price book. Encode the ID as a path component. Each consuming extension retains its own host grant to that folder. For a dataset inside an open `.isap`, use its captured project grant.
A cached extension group folder can support offline reads for the same launch scope. Repeat authoritative root discovery on a later online launch. The ensure command also registers the current group folder with the host event bridge.
First-time group-folder provisioning is online-only.
## 20.4 Canonical layout
Project extensions use the selected host-granted project path and document their own schema within it:
```text
<project-path>.isap/
project.json
extensions/<extension-id>/
project-state/current.json
assets/<immutable-id>-<sha256>.<ext>
```
Immutable sources, media and exports are uploaded before the extension’s mutable commit document. Optional aggregate indexes are derived accelerators; canonical inventory must be sufficient to repair them. The root manifest contains basic project identity/metadata, while ISA Projects owns planning and detailed overview data. Group-only catalogs remain in the extension group folder.
For ISA Quote acceptance, `projects/<project-id>/workflow/award/current.json` is the only canonical commit point. `workflow/export-state/current.json` and the workspace file manifest are derived state: failure to update either one queues repair but does not roll back or invalidate a successfully committed award. Repeated writes use one stable operation ID. Every mutation must use the authoritative award entry on which the UI state was based as its CAS base; an internal fresh read may validate that base but must never silently rebase a stale full-document mutation. A remote CAS conflict is resolved by loading the newest award instead of issuing a compensating write. Manifest repair rereads the current canonical award and only repairs its index entry. Export repair is tied to the committed award revision and is discarded when that award has already been superseded.
Derived workflow repair journals are keyed by immutable launch context and project ID. The launch-context identity always contains the workspace ID, including launches without a group, and adds the group ID when present. A late canonical commit may journal a repair under its captured context after the UI has switched workspaces, but reconciliation may run only when that exact context is active. A resolved canonical upload acknowledgement remains valid for its captured context after a switch; derived index and export work is journaled for that old context instead of being run in the new one. A journal from workspace A must never read or write project data in workspace B, even when both workspaces contain the same project ID.
## 20.5 Writes and metadata
Dashboard-first canonical writes follow the ISA Quote transport pattern:
```js
await bridge.invoke('filesystem_upload_files', {
workspaceId,
files: [{
path: canonicalPath,
filename: 'current.json',
text: JSON.stringify(project),
contentType: 'application/json; charset=utf-8',
resourceType: 'example.project_state',
replaceExisting: true,
metadata: {
kind: 'project_state',
schemaVersion: '1',
projectId,
updatedAt: project.updatedAt
}
}]
});
```
All metadata values must be strings. `kind`, `schemaVersion`, the relevant
project identity, and `updatedAt` should be present on canonical files.
`resourceType` should be stable and extension-specific.
Do not add `syncable: "true"` to dashboard-first writes. That exact value
selects a different transport: the optional local/offline reconciliation queue.
For writes:
- upload immutable assets with `replaceExisting: false`;
- upload the canonical project document last;
- replace a mutable canonical path with `replaceExisting: true`;
- pass `expectedSyncRevision` and `expectedContentHash` when the host returned them, while continuing to address the file by canonical path;
- use a stable 64-hex `metadata.client_operation_id` when retrying one
idempotent online create.
The Filesystem API exposes only `filesystem_upload_files` for writes, for one to 256 items. Dashboard-first and syncable items share the same request envelope; every syncable item must carry the exact `metadata.syncable = "true"` value, and every returned item is an independent locally durable pending result. A missing dashboard file ID is normal until reconciliation confirms a new path. Use the local path and content hash as provisional identity, observe `filesystem-sync-state-changed`, query `filesystem_query_index`, or inspect sync metadata returned by `filesystem_list_dir` and `filesystem_get_files` only when upload statistics matter to the extension, and do not block the local UI on dashboard acceptance. The host replays queued files with bounded concurrency and prioritizes smaller files.
A project is saved only after the canonical upload succeeds. A failed derived
index update is a repair condition, not a failed canonical commit.
Canonical reads distinguish four explicit policies:
- `dashboard-required` bypasses pending and clean caches, never falls back to cached bytes, and is mandatory before CAS writes or applying a remote canonical document;
- `dashboard-first` preserves a pending local edit, otherwise reads the dashboard and uses a clean cache only when the dashboard is unavailable; and
- `cache-preferred` may return a complete clean cache immediately and is reserved for non-authoritative presentation reads; and
- `cache-only` reads pending or complete clean local bytes without requesting a dashboard link or download. A content miss returns an item-level `status: "unavailable"`, `authoritative: false`, `source: "cache"`, and `reason: "cache-miss"` result so callers can poll without treating the miss as an authoritative deletion.
The read surface consists of `filesystem_list_dir` and `filesystem_get_files`. Listing merges dashboard inventory with locally available syncable entries and returns whether the inventory is authoritative. With `cachePolicy: "cache-only"`, listing performs no dashboard RPC and returns only files whose bytes are already completely readable from the local sync cache; an empty list is non-authoritative and suitable for polling. `filesystem_get_files` is the bounded, unified content command for one file or a batch. Its default local-first policy uses only complete clean host-cache entries for syncable files, then retrieves unresolved paths from the dashboard. It is selected solely by canonical paths and validates supplied revision/hash preconditions before exposing an item. A missing cache path or metadata mismatch is not evidence that a dashboard file was deleted. Use `cache-only` for local polling that must never cause network retrieval. Canonical project application, authoritative absence checks, remote inventory, and CAS preparation must specify `cachePolicy: "dashboard-required"` with canonical paths and every available revision/hash precondition.
An authoritative file response couples the downloaded bytes with the workspace file ID, canonical path, artifact ID, sync revision, optional server SHA-256, and update timestamp obtained for that same file generation. When a server hash is present, the host verifies the downloaded bytes before exposing it as a CAS hash. A historical file without a server hash may still be authoritative by identity and revision, but the client must keep its server hash empty and must never promote a locally calculated digest to a server CAS precondition.
Creating a canonical path must be create-only after an authoritative `absent` result. Replacing it requires the file ID and every available revision/hash precondition from the authoritative read. Dashboard upload initialization and extension intermediate-folder creation share a transactional workspace path fence, re-read their parent and target inside the transaction, and use bounded reconciliation after an uncertain commit. This closes the first-create race as well as the ordinary replacement race.
Each canonical project document carries a monotone `generation`. Every successful content or lifecycle transition advances it from the highest authoritatively discovered generation for that project. Candidate selection compares document generation first, then the coupled server revision, and uses timestamps only as a compatibility fallback for legacy documents. A listing timestamp or derived manifest timestamp must never make an older document win. Project-create reconciliation likewise requires a `dashboard-required` `found` or `absent` result; cached bytes cannot confirm whether a create committed.
## 20.6 Incoming reconciliation
A successful outbound write is only half of project sync. Every project
extension must also discover dashboard changes while it remains open.
The extension must:
- inventory canonical project documents at startup;
- refresh at a bounded interval; 30 seconds is the default when the host does not advertise an authoritative indexed-cache event capability;
- when that capability is available, consume its scoped change batches immediately and run an authoritative recovery audit at least every five minutes;
- refresh when the iframe regains focus or becomes visible on hosts without the indexed-cache event capability;
- refresh the Shared Project Registry too, when it is used;
- validate document schema, identity, and canonical path before accepting it;
- merge remote additions, updates, archives, and removals;
- retain the last usable generation when an inventory request is unavailable;
- isolate a malformed project instead of disabling the complete repository; and
- never overwrite an unsaved, dirty, pending, or conflicted local draft.
Canonical inventory code must preserve `found`, `absent`, `invalid`, and
`unavailable` as distinct outcomes. Convenience helpers that collapse errors to
`null` or `[]` must not drive deletion or migration decisions.
When active, archived, tombstone, and purge candidates exist, inventory reads every candidate returned by the authoritative listing before selecting the winner. The lifecycle inside the selected canonical document is authoritative; its physical path may remain stable across archive and restore to preserve file identity and CAS continuity. Tombstones and purge markers are physical canonical JSON files with a higher project generation, not manifest-only flags. When a stale active write races a marker and both expose the same explicit generation, the deletion marker wins before timestamps are considered; only a deliberate recreation based on that marker may advance to the next generation and become active again. The manifest is repaired from the selected canonical file and is never allowed to select or republish an older canonical document. Canonical inventory therefore remains usable when the derived manifest is unavailable.
Generic filesystem state events may trigger an immediate refresh, but they are not an authoritative reconciliation mechanism. A host may advertise a dedicated post-reconciliation indexed-cache event whose changed/deleted paths are safe to use as an accelerator. The extension must still inventory at startup, preserve unavailable-versus-absent semantics, and run the bounded authoritative recovery audit because dashboard-first writes do not depend on the offline sync worker.
## 20.7 Conflicts and deletion
When replacement preconditions report a conflict, automatic saving stops. Keep
the local draft and its last known base, then offer an explicit choice such as
loading the shared version or saving the local work as a copy. Never silently
overwrite or rebase a newer shared document.
Deletes use validated canonical paths and the latest revision/hash preconditions when available. An unavailable inventory is not proof that a project was deleted. Archiving a Shared Project Registry record must preserve its ID and must not move or delete extension-owned files.
For an extension-owned project delete or purge, commit and verify the physical tombstone or purge marker before deleting project files or local derived state. Cleanup must inventory both the active and archive paths directly from the dashboard and proceed only when both listings are authoritative. Cleanup must preserve the marker. If inventory or cleanup is interrupted, the higher-generation marker and local project state remain available for retry; the marker still wins over leftover project bytes and prevents resurrection.
## 20.8 Validation
At minimum, test:
- device A saves and a separate device B repository discovers the project;
- a mounted device discovers a remote create, update, archive, and removal;
- focus and interval refresh retain dirty local work;
- a transient unavailable listing retains the last usable generation;
- one malformed canonical document does not hide valid projects;
- root discovery runs on each mounted online launch;
- immutable assets commit before the mutable project document;
- replacement conflicts do not silently overwrite remote content;
- stale cached project bytes are never combined with metadata from a newer listing;
- equal or misleading timestamps cannot beat a higher canonical project generation;
- archive, restore, delete, and deterministic-ID recreation preserve monotone generations without reusing a tombstone as a live write base;
- canonical reads still select the correct project or purge marker while the derived manifest is unavailable;
- interrupted delete cleanup leaves a physical higher-generation marker that prevents old project bytes from being resurrected;
- an unavailable active or archive inventory stops shared and local delete cleanup after the canonical marker commit;
- switching between a group and a group-less context clears the old extension root and manifest before another project read or write;
- an authoritative retry bypasses a stale host cache;
- a committed award remains successful when export-state or manifest repair fails;
- a stale second client cannot overwrite a newer canonical award;
- an old repair journal cannot replay an older award or export over a newer award;
- a repair journal captured in workspace A cannot replay in workspace B, even for the same project ID;
- Shared Project Registry IDs remain stable across archive and restore; and
- the extension's full package build succeeds.
If offline editing is enabled, also test restart-offline reads, offline saves,
reconnect confirmation, and simultaneous-edit conflict handling against a
dashboard that advertises the exact file-sync protocol.