diff --git a/README.md b/README.md index 4b4de4e..1c50a49 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,9 @@ ## Documents +- **[Accepted contract registry](spec/contract-registry.md)** — consolidated scope, + approval basis, normative sources and open implementation boundaries (D-001–D-074). + - [`rfc/RFC-0001-architecture.md`](rfc/RFC-0001-architecture.md) — system architecture, boundaries, core invariants. - [`rfc/RFC-0002-layers-and-overlays.md`](rfc/RFC-0002-layers-and-overlays.md) — OSTree-backed layers, purpose layers, managed overlays and host extensions. - [`rfc/RFC-0003-build-and-composition.md`](rfc/RFC-0003-build-and-composition.md) — initial build/composition pipeline and filesystem contract. @@ -31,6 +34,28 @@ - [`examples/managed-overlay.yaml`](examples/managed-overlay.yaml) — illustrative managed overlay manifest. - [`examples/host-extensions.yaml`](examples/host-extensions.yaml) — illustrative local host extension state. +## Implementation contracts and drafts + +- [Terra deployment and desktop updates](spec/terra-infrastructure.md), accepted D-071: + source registries, mirror integration, standalone deployment and CLI/UI direction. + +- [Frozen Layer YAML/JSON v1](schemas/README.md), accepted D-070; + [block-by-block agreement](spec/layer-yaml-freeze.md). + +- [RFC-0008](rfc/RFC-0008-manifests-locks-and-artifacts.md): manifests, two lock stages, identities and layer/package artifacts. +- [RFC-0009](rfc/RFC-0009-cli-contract.md): complete CLI coverage and operation lifecycle. +- [RFC-0010](rfc/RFC-0010-docker-build-and-distribution.md): Docker/cron, HTTP registry, pinning, net install and ISO portal. +- [RFC-0011](rfc/RFC-0011-package-actions-compatibility.md): mandatory Core/KDE/GNOME package-action compatibility. +- [Approval review](spec/contracts-v1-review.md), [package-action implementation plan](spec/package-actions-plan.md), [draft v1 examples](examples/v1/README.md). + +RFC-0008 semantics are accepted by D-066 (2026-11-04); concrete schemas/adapters +remain pending. RFC-0009/D-067 CLI coverage and lifecycle are accepted (2026-11-04) +for incremental delivery. RFC-0010/D-068 infrastructure/publication is accepted +(2026-11-04), with deployment bindings and isolation validation pending. +RFC-0011/D-069 and its implementation plan are accepted (2026-11-04); exact desktop +manifests, transition matrix and implementation evidence remain pending. +D-061 accepts only RFC-0001–0007. + ## RFC status vocabulary - **Draft** — under discussion. diff --git a/examples/v1/README.md b/examples/v1/README.md new file mode 100644 index 0000000..2e440ab --- /dev/null +++ b/examples/v1/README.md @@ -0,0 +1,25 @@ +# Layer v1 examples and composition review fixture + +Layer syntax is frozen by D-070; see the [schema](../../schemas/README.md). +These are illustrative package sets, not working or fully approved build profiles. +The current prototype does not yet implement this manifest API. JSON and the strict +YAML subset represent the same source model. Composition syntax remains a review fixture. + +- `core.layer.yaml`, `gnome.layer.yaml`, `kde.layer.yaml`: complete examples of + the frozen Layer syntax; desktop contents and referenced adapters remain illustrative. + +- `core.layer.json`: Core package requirements and a minimal runtime check. +- `gnome.layer.json`: role/variant, target service, native provisioner and functional + check declaration. Package list is deliberately incomplete; no functioning GNOME + image or implementation of the referenced adapters is implied. +- `marker.layer.json` plus `files/test-marker`: layer-authored payload. +- `core.composition.json`: Core-only selection and explicit overlay ordering. + +Profile and adapter names are logical proposed IDs, resolved to exact digests in +locks. A bare logical profile name is not enough to execute a build. Discovery refs +must resolve to a single matching snapshot before a CompositionLock is emitted. + +Required lock fields and artifact layout are specified in RFC-0008. Exact generated +lock fixtures and canonicalization vectors are an approval/implementation +gate, not invented hashes in an apparently executable example. Older sibling YAML +examples remain historical illustrations and are not silently migrated. diff --git a/examples/v1/core.composition.json b/examples/v1/core.composition.json new file mode 100644 index 0000000..89f8fd5 --- /dev/null +++ b/examples/v1/core.composition.json @@ -0,0 +1,15 @@ +{ + "apiVersion": "archipelago/v1", + "kind": "Composition", + "metadata": {"name": "core-x86_64"}, + "spec": { + "architecture": "x86_64", + "snapshot": {"ref": "snapshots/monthly/current"}, + "core": {"ref": "layers/core/arch"}, + "purpose": null, + "overlays": [{"ref": "layers/overlay/test-marker"}], + "boot_profile": "uefi-systemd-boot-ext4/v1", + "validation_profile": "core-vm/v1", + "installer_profiles": ["core-offline/v1", "core-net/v1"] + } +} diff --git a/examples/v1/core.layer.json b/examples/v1/core.layer.json new file mode 100644 index 0000000..8dfa7e1 --- /dev/null +++ b/examples/v1/core.layer.json @@ -0,0 +1,23 @@ +{ + "apiVersion": "archipelago/v1", + "kind": "Layer", + "metadata": {"name": "core/arch", "version": "0.1.0"}, + "spec": { + "type": "core", + "architecture": "x86_64", + "packages": {"runtime": [{"name": "archipelago"}, {"name": "base"}, {"name": "linux"}, {"name": "ostree"}]}, + "runtime": { + "units": [ + {"name": "systemd-networkd.service", "activation": "enable"}, + {"name": "systemd-resolved.service", "activation": "enable"} + ], + "boot_checks": ["core-ostree-boot"] + }, + "actions": [{ + "id": "core-ostree-boot", "phase": "runtime", "adapter": "exec/v1", + "argv": ["/usr/bin/test", "-e", "/run/ostree-booted"], + "inputs": ["/run/ostree-booted"], "outputs": [], "after": [], + "timeout_seconds": 10, "required": true, "network": "none" + }] + } +} diff --git a/examples/v1/core.layer.yaml b/examples/v1/core.layer.yaml new file mode 100644 index 0000000..bcac828 --- /dev/null +++ b/examples/v1/core.layer.yaml @@ -0,0 +1,32 @@ +# Frozen Layer v1 syntax; illustrative package set, not a complete build profile. +apiVersion: archipelago/v1 +kind: Layer +metadata: + name: core/arch + version: 0.1.0 +spec: + type: core + architecture: x86_64 + packages: + runtime: + - name: base + - name: linux + - name: linux-firmware + - name: archipelago + - name: ostree + runtime: + provisioner: terminal-firstboot/v1 + units: + - name: systemd-networkd.service + activation: enable + - name: systemd-resolved.service + activation: enable + boot_checks: [core-ostree-boot] + actions: + - id: core-ostree-boot + phase: runtime + adapter: exec/v1 + argv: [/usr/bin/test, -e, /run/ostree-booted] + inputs: [/run/ostree-booted] + timeout_seconds: 10 + network: none diff --git a/examples/v1/files/test-marker b/examples/v1/files/test-marker new file mode 100644 index 0000000..593bdcb --- /dev/null +++ b/examples/v1/files/test-marker @@ -0,0 +1 @@ +Archipelago managed overlay test diff --git a/examples/v1/gnome.layer.json b/examples/v1/gnome.layer.json new file mode 100644 index 0000000..8f2986e --- /dev/null +++ b/examples/v1/gnome.layer.json @@ -0,0 +1,21 @@ +{ + "apiVersion": "archipelago/v1", + "kind": "Layer", + "metadata": {"name": "purpose/desktop/gnome", "version": "0.1.0"}, + "spec": { + "type": "purpose", "architecture": "x86_64", + "purpose": {"role": "desktop", "variant": "gnome"}, + "compatibility": {"core": ["core/arch"]}, + "packages": {"runtime": [{"name": "gdm"}, {"name": "gnome-initial-setup"}, {"name": "gnome-shell"}]}, + "runtime": { + "units": [{"name": "gdm.service", "activation": "enable"}], + "provisioner": "gnome-initial-setup/v1", + "functional_checks": ["gnome-session"] + }, + "actions": [{ + "id": "gnome-session", "phase": "runtime", "adapter": "gnome-session-check/v1", + "argv": [], "inputs": ["gdm.service"], "outputs": [], "after": [], + "timeout_seconds": 180, "required": true, "network": "none" + }] + } +} diff --git a/examples/v1/gnome.layer.yaml b/examples/v1/gnome.layer.yaml new file mode 100644 index 0000000..9f574f1 --- /dev/null +++ b/examples/v1/gnome.layer.yaml @@ -0,0 +1,32 @@ +# Illustrative package set and adapter references; not a certified desktop. +apiVersion: archipelago/v1 +kind: Layer +metadata: + name: purpose/desktop/gnome + version: 0.1.0 +spec: + type: purpose + architecture: x86_64 + purpose: + role: desktop + variant: gnome + compatibility: + core: [core/arch] + packages: + runtime: + - name: gdm + - name: gnome-shell + - name: gnome-initial-setup + runtime: + units: + - name: gdm.service + activation: enable + provisioner: gnome-initial-setup/v1 + functional_checks: [gnome-session] + actions: + - id: gnome-session + phase: runtime + adapter: gnome-session-check/v1 + inputs: [gdm.service] + timeout_seconds: 180 + network: none diff --git a/examples/v1/kde.layer.yaml b/examples/v1/kde.layer.yaml new file mode 100644 index 0000000..aa009a3 --- /dev/null +++ b/examples/v1/kde.layer.yaml @@ -0,0 +1,30 @@ +# Illustrative package set; Core provisioning is inherited, native KDE adapter pending. +apiVersion: archipelago/v1 +kind: Layer +metadata: + name: purpose/desktop/kde + version: 0.1.0 +spec: + type: purpose + architecture: x86_64 + purpose: + role: desktop + variant: kde + compatibility: + core: [core/arch] + packages: + runtime: + - name: plasma-desktop + - name: sddm + runtime: + units: + - name: sddm.service + activation: enable + functional_checks: [kde-session] + actions: + - id: kde-session + phase: runtime + adapter: kde-session-check/v1 + inputs: [sddm.service] + timeout_seconds: 180 + network: none diff --git a/examples/v1/marker.layer.json b/examples/v1/marker.layer.json new file mode 100644 index 0000000..6c446ce --- /dev/null +++ b/examples/v1/marker.layer.json @@ -0,0 +1,13 @@ +{ + "apiVersion": "archipelago/v1", + "kind": "Layer", + "metadata": {"name": "overlay/test-marker", "version": "0.1.0"}, + "spec": { + "type": "overlay", "architecture": "x86_64", + "compatibility": {"core": ["core/arch"], "requires": [], "before": [], "after": [], "conflicts": []}, + "files": [{ + "type": "file", "source": "files/test-marker", "path": "/usr/share/archipelago/test-marker", + "mode": "0644", "owner": "root", "group": "root" + }] + } +} diff --git a/rfc/RFC-0001-architecture.md b/rfc/RFC-0001-architecture.md index f1191d2..63d1dc3 100644 --- a/rfc/RFC-0001-architecture.md +++ b/rfc/RFC-0001-architecture.md @@ -12,6 +12,9 @@ Archipelago is an Arch Linux-based, OSTree-managed generic Linux distribution an It provides a declarative way to build, publish, install, update, rebase, roll back and manage operating-system compositions. It also manages selected runtime workloads while preserving the standard Linux filesystem and execution contracts. +D-062 selects Rust for the primary `archipelago` binary and its functional modules. Laboratory tooling +may use other languages; exact FFI/adapter interfaces remain implementation contracts. + The project must support three execution contexts through one primary `archipelago` CLI/binary: 1. **Build host** — build packages, layers, compositions, releases and installer artifacts from a supported Linux host. @@ -172,6 +175,12 @@ Runs on an installed Archipelago host. It manages desired state, status, update, Runs in a live environment. It provisions storage, initializes the target OSTree repository/deployment, installs a selected image and configures boot integration. +D-064 includes installation and first-run control in the unified binary's live and +installed contexts. Support deferred primary-user provisioning on the first installed +boot, terminal onboarding for Core and native GNOME/KDE setup tools where feasible. +Frontend integration belongs to the concrete Purpose. This does not select a daemon, +stable GUI API or partition profile; see RFC-0006 §4.1 for the account boundary. + ## 6. Execution contexts The `archipelago` binary must expose functionality appropriate to its execution context. diff --git a/rfc/RFC-0002-layers-and-overlays.md b/rfc/RFC-0002-layers-and-overlays.md index ed914f8..613b0ce 100644 --- a/rfc/RFC-0002-layers-and-overlays.md +++ b/rfc/RFC-0002-layers-and-overlays.md @@ -164,7 +164,9 @@ The ordering is logical and does not imply OSTree has native layer stacking. The Core is built from the Arch Linux `base` metapackage plus the `linux` kernel package. This is the initial foundation, not an exhaustive package list: -additional firmware and boot/deployment integration inputs must be specified. +D-074 adds `linux-firmware` explicitly with its normal dependency closure, in Core +and the live installer. Do not rely on an incidental `linux` dependency. Further +hardware-specific firmware and boot/deployment integration inputs require review. Arch Core provides the generic Linux foundation, including: diff --git a/rfc/RFC-0003-build-and-composition.md b/rfc/RFC-0003-build-and-composition.md index 18e97f9..1b1f170 100644 --- a/rfc/RFC-0003-build-and-composition.md +++ b/rfc/RFC-0003-build-and-composition.md @@ -64,6 +64,11 @@ signature, dependency and final-composition validation. ### Package selection +D-063 schedules monthly repository snapshots, with ZFS-based creation on the mirror +host deferred until a working experimental `archipelago-core-latest.iso` exists. +This delivery order does not relax D-043 identity or D-050 public release gates. +An experimental latest filename is not a snapshot identity or a public-channel release. + Default package flow: 1. Resolve a package from a pinned binary repository. 2. Verify package identity and integrity. diff --git a/rfc/RFC-0006-system-accounts.md b/rfc/RFC-0006-system-accounts.md index 5874367..9079002 100644 --- a/rfc/RFC-0006-system-accounts.md +++ b/rfc/RFC-0006-system-accounts.md @@ -139,6 +139,21 @@ D-036 removes universal latest-account/credential continuity as an MVP blocker. Exact initial provisioning, recovery instructions and interrupted-transition tests remain to be specified within the native OSTree model. +### 4.1 Deferred first-run provisioning (D-064) + +Installation may defer primary-user creation to onboarding in the first booted +deployment. Complete it before preparing subsequent normal rollback targets (D-036). +Core provides a terminal CLI setup flow; GNOME/KDE Purpose variants should reuse +native initial-setup tools where feasible. A new-user wizard runs before the first +ordinary user login; later per-user welcome/customization is a distinct lifecycle. + +Use standard account mechanisms and deployment-local `/etc`. GUI and CLI integration +must preserve existing identities and allow interrupted provisioning to be retried. +Adding a desktop Purpose to an already provisioned Core must preserve its primary user. +Exact frontend selection, completion evidence, resume protocol, setup-session privileges +and systemd ordering remain implementation contracts. A shared `/var` completion flag +alone cannot prove that the booted deployment's `/etc` contains the expected account. + ## 5. Acceptance criteria - First boot creates declared service identities before dependent services start. @@ -155,6 +170,8 @@ remain to be specified within the native OSTree model. credentials and shared-data ownership against the explicitly chosen transition policy; unconditional identity continuity is not assumed after D-032. - Interrupted provisioning can be retried without duplicate identities or data loss. +- Deferred first-run onboarding creates a usable primary user before subsequent + deployments; completed setup is not repeated on ordinary reboot or Purpose addition. ## 6. Open implementation questions diff --git a/rfc/RFC-0007-ostree-platform-integration.md b/rfc/RFC-0007-ostree-platform-integration.md index f208369..09f97b4 100644 --- a/rfc/RFC-0007-ostree-platform-integration.md +++ b/rfc/RFC-0007-ostree-platform-integration.md @@ -148,6 +148,12 @@ continuity and document later-user recovery under these native semantics. ## 6. Boot and activation +D-065 selects an experimental x86_64 UEFI VM installation profile with GPT, +FAT32 ESP and ext4 root, systemd-boot, no encryption or Secure Boot. A separate +`/boot` may be added if required by integration. Validate the complete live-ISO +installation and disk boot before claiming this profile works; the experimental +choice does not freeze all partition/artifact contracts or satisfy public release gates. + The initial bootloader is systemd-boot (UEFI). GRUB 2 is not a required initial backend. Native OSTree deployment and BLS mechanisms should be reused, with actual systemd-boot boot-entry discovery/selection tested rather than assumed. diff --git a/rfc/RFC-0008-manifests-locks-and-artifacts.md b/rfc/RFC-0008-manifests-locks-and-artifacts.md new file mode 100644 index 0000000..090204f --- /dev/null +++ b/rfc/RFC-0008-manifests-locks-and-artifacts.md @@ -0,0 +1,317 @@ +# RFC-0008: Manifest, Lock and Artifact Contracts + +- **Status:** Accepted — D-066, 2026-11-04; scope and remaining details below +- **Version:** 0.1 +- **Date:** 2026-11-04 +- **Scope:** Accepted manifest/lock/artifact semantics; no implementation or migration is implied +- **Depends on:** RFC-0001–0007, D-023–D-026, D-038–D-044, D-058/D-059 + +## 1. Goal and boundary + +Specify interoperable inputs for independent layer builds, composition, registries, +updates and installation. Existing YAML examples and prototype on-disk files are +not this API. The `archipelago/v1` name is reserved by this contract, not released. +D-066 accepts strict YAML/JSON intent manifests, separate LayerLock/CompositionLock, +SHA-256 canonical JSON identities independent of transport, indexed per-package +payload in layer commits, and effective ALPM records with retained originals and +explicit transformation provenance. Concrete schemas and adapters remain to be +validated; RFC-0009–0011 are not approved by this decision. +The Layer YAML/JSON schema was subsequently frozen by D-070; see +[normative schema and validation rules](../schemas/README.md). Composition/lock +schemas and adapters still need implementation before a producer can claim support. + +## 2. Serialization and identity + +The [Layer YAML freeze review](../spec/layer-yaml-freeze.md) records incremental +approval of concrete schema blocks; the envelope/package, runtime, actions, files, +overrides, compatibility, package-replacement and kernel-binding blocks were +agreed on 2026-11-04. The final validation block and complete Layer v1 freeze were +approved the same day (D-070); the review records all agreed sections. + +- Source manifests: UTF-8 YAML 1.2 JSON-compatible subset, or JSON. Reject duplicate + keys, aliases/merge keys, custom tags, non-string map keys, floats, unknown fields + and path traversal. Integers are limited to the interoperable JSON integer range. +- Generated locks/descriptors/indexes: JSON. Canonical identity uses RFC 8785 JCS + after explicit defaults below are expanded; object-key order is insignificant, + array order remains significant. A default change requires a schema version change. +- Common envelope: `apiVersion`, `kind`, `metadata`, `spec`. `metadata.name` is a + logical ID (`[a-z0-9][a-z0-9._-]*` components separated by `/`, max 128 bytes); + optional `metadata.version` is SemVer for authored layers, not an Arch package version. + `Layer` requires that version; other kinds may omit it. +- Content identity: `sha256:<64 lowercase hex>`. Native OSTree commit checksums stay + bare 64-hex values in explicitly named `commit` fields. Do not interchange the two. +- Artifact digest is external to the hashed document: no self-digest, signatures, + download URLs, observed build times or job IDs inside its identity-bearing body. + Deterministic provenance inputs belong inside; execution observations and signatures + are separately bound attestations. URLs are transport bindings, never identities. +- Arrays that represent sets (package names, required IDs) must be unique and sorted + lexicographically in generated documents. Composition order, repository priority, + argv and action order are ordered lists and must never be sorted implicitly. +- Missing optional lists default to `[]`, optional maps to `{}`, Purpose to `null`. + Required scalar fields have no implicit defaults. Explicit null is allowed only + where specified. Unsupported versions are errors, not best-effort parsing. + +## 3. Layer manifest (`kind: Layer`) + +| `spec` field | Contract | +|---|---| +| `type` | Required: `core`, `purpose` or `overlay` | +| `architecture` | Required single target architecture; initially `x86_64` | +| `purpose` | Required `{role, variant}` only for Purpose; role `desktop/server/iot`; forbidden otherwise | +| `packages.runtime` | Unique package requirement objects `{name, constraint?}`; Arch/libalpm version semantics | +| `packages.build` | Build-only requirements; must not leak into runtime by incidental installation | +| `packages.replacements` | `{target, replacement, expected_owner, reason}`; never inferred from pacman `replaces` | +| `compatibility` | `core`/`purpose` allowed-ID lists, `requires`/`conflicts` overlay IDs, `before/after` IDs, optional exact `kernel` identity | +| `files` | Source-tree file entries `{source, path, mode, owner, group}`; no shell interpolation or host-absolute source paths | +| `overrides` | Explicit operations described below; no global overwrite permission | +| `actions` | Declared build/finalize/deploy/runtime actions described below | +| `runtime` | `sysusers`, `tmpfiles`, `units`, `presets`, `boot_checks`, `functional_checks` referencing packaged files/actions | + +Package groups, unconstrained AUR URLs and implicit source builds are not package +names. Source-built packages have separate pinned recipes in the SourceSet and +must enter the selected snapshot before layer resolution. The layer source does +not pin a lower layer commit. A layer build resolves against an explicit snapshot; +the resulting layer artifact and LayerLock record that exact snapshot. +`constraint` is one libalpm comparison (`=`, `>=`, `<=`, `>` or `<` followed by an +Arch version); absent means any version in the selected snapshot. Requirements from +different layers are intersected, not overwritten. Empty compatibility allowlists +mean no additional ID restriction; missing required overlays still fail explicitly. + +`compatibility` is a constraint, not permission to select dependencies silently. +Absent exact kernel constraints mean “no kernel-bound payload”, not “any ABI is safe”. +Kernel-bound inputs identify package checksum, release, architecture and ABI digest. +Providers/virtual package choices are resolved by libalpm and recorded in the lock. +Optional dependencies are installed only when explicitly requested. + +Compatibility field applicability is strict: `core` is allowed on Purpose/Overlay, +`purpose` only on Overlay, `requires`/`conflicts` on Purpose/Overlay, and +`before`/`after` only on Overlay. Reject these fields on other types. Lists default +to empty and reject duplicates. A nonempty Purpose allowlist requires a matching +present Purpose. Requirements/conflicts reference Overlay IDs; ordering constraints +apply to present overlays, with `requires` used separately to require presence. +Missing dependencies, conflicts and cycles fail without silently changing order. +Core/Purpose versions are not pinned here; CompositionLock binds exact commits. +`compatibility.kernel` is optional and permits one exact binding per layer. When +present, all of `package.{name,version,architecture,archive_sha256}`, `release`, and +`abi.{adapter,digest}` are required. Archive and ABI digests use `sha256:<64 lowercase +hex>`. Release identifies the kernel's `/usr/lib/modules/` directory. A versioned +ABI adapter defines the hashed inputs; its code identity is locked. Validate these +values against pinned artifacts; any package/architecture/release/ABI mismatch +blocks composition. The concrete ABI algorithm still requires specification and +validation before use; the example name `linux-module-abi/v1` is not an implemented +capability. Detected modules without a binding are errors. Core supplying the kernel +does not thereby depend on a lower kernel. DKMS sources are distinct from prebuilt +modules: finalization binds their build to the selected kernel and validates results. + +`packages.replacements` defaults to empty, is allowed on Purpose/Overlay and is +forbidden on Core. Each entry requires `target`, `replacement`, `expected_owner` +(effective owning layer ID) and `reason`. The replacement must be explicitly listed +in runtime requirements. A missing target or owner mismatch fails. Whole-package +replacement requires dependency, file-conflict and ABI validation of the complete +result; it is distinct from file overrides and never inferred from pacman `replaces`. + +### Files and overrides + +`path` is an absolute canonical runtime path; `/bin`, `/sbin`, `/lib`, `/lib64` +aliases are normalized using the locked Arch filesystem profile, before conflict +checks. Sources are regular files, explicit directories or symlink objects; symlink +targets are not traversed while applying operations. `mode` is an octal string. +`owner/group` reference root or declared system identities; the lock records numeric +ownership and its resolution evidence. No new global UID/GID registry is introduced. +Unresolved/dynamic ownership of immutable payload blocks the relevant feature. + +File entry `type` defaults to `file` and permits `file/directory/symlink`. A file +requires `source`, a symlink requires literal `target`, a directory has neither. +All entries require `path`, `mode`, `owner`, `group`; conflicting source/target +fields are invalid. Source bytes are part of SourceSet and are hashed in the lock. +`files` defaults to an empty list. Sources are relative to the locked source tree; +parent traversal and escape through symlinks are forbidden. Directory declarations +never imply recursive copying: each contributed object is explicit. Symlink mode +is `"0777"` under Linux semantics and never changes target permissions. Declaring +a file does not itself authorize overwriting another owner's object. + +Each override contains `operation`, an explicit finite `paths` list, +`expected_owner: {layer, package?}`, `reason`, and optional `expected_sha256`. +`expected_sha256`, when present, is a map from a member of `paths` to its digest. +The list and reason are nonempty; layer is required. Package is required for package +objects and absent for layer-authored objects. Check ownership against the composition +index immediately before the operation; mismatches fail. `expected_sha256` uses +`sha256:<64 lowercase hex>` over ordinary-file bytes only; reject directory/symlink +entries. Overrides default to an empty list and share a format across Purpose and +Managed Overlays. +Operations: `replace-file`, `replace-symlink`, `set-metadata`, `change-type`, +`delete-path`. Type changes/deletions enumerate affected children; no implicit +recursion, glob expansion or whole-package removal disguised as file deletion. +Permissions and actual effects are retained independently in provenance. +Replace/change-type operations reference matching new entries in `files`; +set-metadata carries a `metadata` map; delete-path supplies no replacement content. +The metadata map is nonempty and permits only `mode`, `owner`, `group`; editing +xattrs/ACLs/capabilities requires a separate schema extension. Overrides affect only +the new image, never delete persistent state or bypass `/etc`, boot and ESP contracts. +Record their effects in diff/provenance and effective package records. + +`/etc` entries become vendor defaults in `/usr/etc`; installed configuration uses +native OSTree merge. `/boot`/ESP entries must go through a locked boot adapter. +Persistent and pseudo-filesystem payload is forbidden without a named, versioned +adapter: `/var`, `/home`, `/root`, `/srv`, `/opt`, `/usr/local`, `/mnt`, `/run`, +`/tmp`, `/dev`, `/proc`, `/sys`. Declarations of sysusers/tmpfiles are normal `/usr` +payload. This proposal does not silently settle the still-open `/opt` adapter. + +### Actions + +An action declares `id`, `phase`, `adapter`, `argv`, `inputs`, `outputs`, `after`, +`timeout_seconds`, `required`, `network`. Phases are exactly the four RFC-0005 phases. +`required` defaults true; timeout is an explicit positive integer and network is +explicitly `none` or `allowed`. Finalizers require `network: none`. +`argv`, `inputs`, `outputs` and `after` default to empty lists; adapters validate +resource types, allowed values and sufficient inputs. Shell programs are versioned source artifacts invoked by explicit +argv, not interpolated YAML strings. Adapter digest, executable inputs and graph +order are locked. Undeclared overlapping outputs, cycles or unclassified package +hooks fail validation. ALPM hooks keep native trigger semantics; inventory maps +each checksum/action to a phase or a justified inapplicable result. +Action IDs are unique within a layer; `after` references local IDs. Composed +identity is the pair of layer ID and action ID. Cross-layer system ordering is +defined by the finalizer adapter DAG. Missing references and incompatible phases +are errors. Phase selects execution context, not automatic invocation: workflows +or runtime references determine when an action runs. Required failures block the +operation; boot failures produce diagnostics without automatic rollback/reboot. +Official profiles cannot downgrade essential checks to optional. Package actions +are inventoried through PackageActionPolicy and need not be manually duplicated +in the layer's actions list. +The minimum Core/KDE/GNOME closure and PackageActionPolicy are proposed in +[RFC-0011](RFC-0011-package-actions-compatibility.md); locks bind that policy digest. +Policy scope uses a separately hashed package-resolution set, not a reverse +reference to the enclosing lock, avoiding a content-identity cycle. + +Runtime `sysusers/tmpfiles/presets` are lists of packaged absolute `/usr` paths; +`units` entries are `{name, activation}` with activation `enable`, `socket`, or +`manual`. Socket activation names the socket unit. Defaults apply initially and +respect subsequent administrator changes. Conflicting unit declarations and presets +are validation errors. There is no separate `display_manager` field: Purpose +declares its DM unit and its activation adapter manages `display-manager.service`. +A DM change requires an explicit plan accounting for administrator selection. + +Checks are action-ID lists with timeout and required/optional behavior. Boot checks +run in the installed target boot lifecycle. Functional checks run in isolated +acceptance environments, never as routine user-boot mutations. Purpose inherits +all Core checks and may add its own. Check execution context must preserve this +distinction even when an action exercises target runtime behavior. + +An optional `provisioner` is a named, versioned adapter reference. Core supplies +terminal firstboot on tty1/ttyS0; Purpose overrides the adapter when declared and +otherwise inherits Core's. Onboarding completes before subsequent normal deployments +and is not repeated on updates. Secrets and machine-specific account databases +cannot appear in the manifest. Runtime lists default to empty; official validation +profiles enforce mandatory declaration completeness. + +## 4. Composition manifest (`kind: Composition`) + +Required fields: `architecture`, `snapshot`, `core`, `boot_profile`, +`validation_profile`. Optional: `purpose: null`, ordered `overlays: []`, +`installer_profiles: []`. + +- A selector is exactly one of `{ref: logical-ref}` or `{commit: checksum}`. + Resolve authenticates the catalog and records the selected immutable artifact. +- `snapshot` selects one immutable descriptor ID or one discovery ref. All selected + layer artifacts must have that ID. Missing layers require an explicit build step, + not a hidden build/download-from-latest during compose. +- Exactly one Core, zero/one Purpose and the listed overlays. Resolve rejects wrong + types, duplicates, missing requirements, cycles and invalid order without reordering. +- Channel/publication is a release concern (RFC-0010), not a magic build input. + Adding an arbitrary overlay does not establish official support. + +## 5. SourceSet, Snapshot and locks + +`SourceSet` records each repository's logical ID, exact Git commit, subdirectory and +source-tree digest, plus toolchain/recipe/adapter inputs. Public builds reject dirty +trees; private experiments may use an explicitly hashed local tree. No secrets are +source inputs. Git remotes and physical checkout paths are replaceable transport. + +`Snapshot` has `architecture`, ordered `repositories`, and a package catalog digest. +Each repository records its ID, database digest/size, optional files DB digest, +package-index digest and signing-policy ID. Catalog entries include repository, +name, Arch version, architecture, filename, size, archive SHA-256 and signature +identity. The snapshot ID is the digest of this canonical descriptor, including +ordered repository identities. Monthly labels are discovery aliases only. + +Two lock kinds avoid a circular dependency between layer creation and composition: + +| Lock | Required exact inputs | +|---|---| +| `LayerLock` | Layer manifest digest, SourceSet digest, snapshot ID, architecture, complete runtime/build dependency resolutions and providers, archive identities, builder OCI digest, bootstrap/toolchain/adapters/action graph and deterministic build parameters | +| `CompositionLock` | Composition manifest digest, snapshot ID, architecture, ordered layer descriptors/commits, effective package-owner plan, explicit replacements/overrides, boot/finalizer/validation inputs and installer profile identities | + +For each package retain explicit-request versus dependency reason. Package IDs are +digests of `{name, version, architecture, archive_sha256}`. Package identities do not +waive snapshot equality. Lock verification checks the complete referenced graph, +including packages, sources and adapters, rather than just filenames. + +Only `resolve`/explicit update creates a changed lock. Build/compose requires a +matching manifest and lock and fails if any locked input is absent or inconsistent. +Changing URLs with identical verified content does not require a new semantic lock. + +## 6. Layer artifact and package database + +Proposed layer tree (ordinary OSTree objects, not a custom object store): + +```text +payload/packages//root/... # indexed package contribution +payload/files/root/... # layer-authored contribution +metadata/manifest.json +metadata/lock.json +metadata/packages.json +metadata/files.json +metadata/actions.json +metadata/provenance.json +``` + +Separate package trees preserve original contributions when paths collide or a +layer-authored override replaces one. OSTree deduplicates identical objects. +`packages.json` retains original ALPM records and archive identity, declared +requirements, package files and adapters applied during isolated layer build. +`files.json` maps every payload object to source path, canonical target, type, +hash/link target, mode, numeric ownership, xattrs/ACLs/capabilities and origin. +Unindexed objects, escaping paths and missing indexed objects fail validation. +Generated shared caches are final-composition outputs, not authoritative package trees. + +Composition selects each package once from layer commits, assigns effective layer +ownership by D-025, applies overrides and builds one image tree. It never reruns +pacman installation to obtain managed layer payload. Original package ALPM metadata +is retained as evidence. The image's ALPM local DB is assembled deterministically +from selected package records and the effective tree, with explicit install reasons, +runtime `/etc` paths and epoch mtimes for immutable OSTree files. + +Every adjusted record must have a transformation record containing original and +effective identities and its responsible layer/adapter. Package ownership and +effective content ownership are distinct: a file override does not pretend the +original archive supplied the new bytes. `archipelago verify --original-packages` +reports these deviations; effective-tree verification checks declared results. +`pacman -Q/-Qo/-Qkk`, backups, generated outputs and non-root ownership require +integration fixtures before this DB adapter is declared conformant. + +Image runtime metadata is a selected subset under `/usr/lib/archipelago/`; layer +`metadata/` is never copied wholesale. An external Image descriptor binds commit, +manifest/lock/source/snapshot identities, effective ownership, finalizer results and +required validation profile. Signatures/observed test runs are external attestations. + +## 7. Compatibility, alternatives and acceptance + +Existing illustrative `schema: archipelago.layer/v1` examples remain historical. +Explicit import produces a draft manifest plus diagnostics; no silent reinterpretation. +Unknown future fields/versions fail closed; compatible producer additions require +a documented version negotiation, not silently ignored semantics. + +Alternatives considered: YAML-only hashes (format-sensitive); one lock for all build +stages (circular layer identities); flattened-only package payload (loses colliding +contributions); reinstalling packages during composition (violates D-026). + +Implementation acceptance requires examples for Core/Purpose/overlay, both lock stages, replacement +and runtime declarations; canonicalization vectors; invalid-input matrix; same +snapshot with conflicting packages; dependency-owner reassignment on overlay removal; +ALPM/effective-tree fixtures; schema migration diagnostics. Implementation then must +pass them. Full reproducibility is a separate release gate, not implied by locks. + +The effective/original ALPM-record model is accepted by D-066 and the Layer schema +is frozen by D-070. The concrete DB adapter, canonical source identity details, +account/boot/cache adapters and remaining Composition/lock/artifact schemas still +require review and validation. Follow-up questions remain open until acceptance. diff --git a/rfc/RFC-0009-cli-contract.md b/rfc/RFC-0009-cli-contract.md new file mode 100644 index 0000000..d260773 --- /dev/null +++ b/rfc/RFC-0009-cli-contract.md @@ -0,0 +1,173 @@ +# RFC-0009: Unified CLI and Operation Lifecycle + +- **Status:** Accepted — D-067, 2026-11-04 +- **Version:** 0.1 +- **Date:** 2026-11-04 +- **Scope:** Complete command coverage and behavior; not a claim of implementation + +## 1. One binary, three contexts + +D-067 accepts the unified command coverage, checked plan/apply lifecycle, shared +results/errors and durable operation records, explicit desired/pending/booted state, +capability reporting and initial operation without a mandatory daemon. Delivery is +incremental. This decision does not approve the infrastructure or package-action +policies proposed separately in RFC-0010/D-068 and RFC-0011/D-069. + +`archipelago` is the Rust entrypoint for build host, installed system and live +installer. Context is detected and reported, then checked per operation. An explicit +`--sysroot` is supported only by commands with a documented offline target contract; +it is not permission to run a live-host operation on an arbitrary directory. +No resident daemon is required in phase one. Existing tools remain the backends. + +`archipelago capabilities --json` must report implemented commands, schema versions, +adapters, architectures and contexts. A command specified here but unavailable in a +binary returns `E_UNSUPPORTED`, never success from a placeholder handler. + +## 2. Command coverage + +The names below define the CLI contract; groups without arguments show help. +Every mutating operation supports inspectable results and stable error codes. + +| Group | Required commands | Context / responsibility | +|---|---|---| +| Global | `version`, `capabilities`, `doctor` | All; versions, capabilities and non-mutating diagnostics | +| Manifests | `manifest init/validate/fmt/schema` | Source authoring and strict validation; fmt preserves semantics | +| Pinning | `resolve layer/composition`, `lock verify/diff` | Explicitly create locks, verify the complete input graph | +| Package actions | `hooks inventory/explain/validate/coverage/test` | Shared policy and mandatory Core/KDE/GNOME coverage (RFC-0011) | +| Snapshots | `snapshot capture/verify/show/list` | Capture controlled repositories, verify immutable identity | +| Builds | `build environment/package/layer/iso` | Locked bootstrap/toolchain/package/layer/installer outputs | +| Composition | `compose plan/build/verify/diff` | Complete image from exact layer commits and a CompositionLock | +| Pipelines | `pipeline plan/run/status/logs/retry/cancel` | Persisted build DAG; scheduling is external cron | +| Registry | `registry list/show/pull/verify/export/import` | Native OSTree plus descriptors/packages; offline bundles preserve identities | +| Releases | `release assemble/verify/publish/promote/withdraw` | Candidates, validation, signed publication and same-commit promotion | +| Portal | `portal generate` | Static download catalog from verified release metadata | +| Host status | `status`, `verify`, `diff` | Booted/pending/desired state, origin, checks and actual local modifications | +| Updates | `update check/plan/apply` | Select complete candidate, reapply full extension set, stage | +| Rebase | `rebase plan/apply` | Explicit change of managed image track/base with compatibility validation | +| Purpose | `purpose list/show/set/clear` | Zero/one concrete Purpose; clear returns to Core-only through recomposition | +| Overlays | `overlay list/show/add/remove/order` | Explicit ordered managed set; no implicit dependency insertion | +| Extensions | `extension enable/add/remove/list/status/history/restore` | Persistent explicit requests, dependencies, generations and retained local files | +| Replacements | `extension override set/reset/list` | Separate whole-package replacement intent; add never implies replacement | +| Deployments | `deployment list/show/pin/unpin/cancel/prune`, `rollback` | Native OSTree selection/retention; rollback selects next boot, no reboot | +| Installation | `install plan/apply/status/resume` | Exact target disk/partitions, input image and durable installation journal | +| Onboarding | `firstboot`, `provision status/resume` | Installed target; CLI on tty1/ttyS0 or declared native Purpose adapter | +| Accounts | `user list/add/remove` | Standard tools; removal only for explicitly classified human accounts | + +`boot-sync` remains an internal lifecycle entrypoint, not a second deployment API. +Workload managers (Flatpak/containers/etc.) require separate contracts: completeness +of this OS CLI does not silently choose a workload subsystem or daemon. + +### Representative syntax + +```text +archipelago resolve layer layer.yaml --snapshot sha256:... --output layer.lock.json +archipelago build layer --manifest layer.yaml --lock layer.lock.json --output DIR +archipelago resolve composition composition.yaml --output composition.lock.json +archipelago compose build --manifest composition.yaml --lock composition.lock.json --output DIR +archipelago build iso --profile installer.yaml --lock installer.lock.json --output DIR +archipelago extension add nano mc +archipelago extension add --file ./custom.pkg.tar.zst +archipelago extension override set TARGET --with-package REPLACEMENT +archipelago update plan --channel testing +archipelago update apply --plan sha256:... +archipelago install plan --disk /dev/disk/by-id/... --release sha256:... +archipelago install apply --plan sha256:... --erase +archipelago rollback --deployment CHECKSUM.SERIAL +``` + +Names, file inputs, refs, channels, package overrides and deployment pins are distinct +arguments. No overloaded “pin” silently means both input locking and GC retention. +Prototype `overlay apply test-marker` and positional `build iso WORK BOOTSTRAP` get +explicit compatibility diagnostics/aliases, not an undocumented semantic change. + +## 3. Shared transaction contract + +Operations follow `select → resolve → plan → execute → validate → commit → publish/stage`. +Plans bind source/manifest/lock IDs, current booted/pending identities, selected +snapshot, desired changes, required adapters and expected effects. A plan ID is a +content digest. Apply rechecks these preconditions under the mutation lock; changed +state requires a new plan. Human-friendly one-step add/set commands may compute and +apply that same internal plan; they must not bypass validation or change semantics. + +Planning may fetch verified metadata and populate a download cache, but cannot mutate +deployments or target disks. `--offline` forbids fetching and reports absent inputs. +Required privileges are checked before mutation. Explicit destructive intent applies +to the identified resource (`--erase` for a disk); `--yes` only answers routine prompts, +never grants implicit package overrides, data deletion or fallback activation. + +Persist an operation ID, phase, exact inputs, log references and terminal result. +Commands may be synchronous; durable operation records are not proof a daemon exists. +Concurrent mutations of one sysroot fail with `E_BUSY`; independent builds may run +within configured limits. SIGINT/cancel stops before the next safe boundary, preserves +diagnostics/inputs and never reports activation if only composition succeeded. +After a crash, resume checks actual state and completed phases. Installation resume +must not reformat a partition already containing the installed target implicitly. + +## 4. Desired, pending and booted state + +- Status distinguishes all three; includes managed base, commit/serial, snapshot, + Purpose, ordered overlays, requested/resolved extensions and support provenance. +- Repeated extension add accumulates requests against the owned staged candidate, + otherwise the booted deployment. Duplicate requests are no-ops. An unrelated or + finalized pending operation must be explicitly reconciled, never discarded silently. +- Each generation is recomposed from its managed base and full requested set; + dependencies remain separate. Remove/override reset uses the same rule. +- After rollback, operations start from the selected deployment's intent; a global + “latest generation” must not silently resurrect newer requests. +- Preparing any change leaves current `/usr` unchanged. No command here implicitly + reboots. Stage replacement happens only after validation; failed reapplication + preserves previous pending/booted/rollback state and retained local inputs. +- Update of an official image selects one authenticated release/image. Custom + composition update resolves a new complete CompositionLock. Neither mixes layers + from different snapshots. Host Extensions are reapplied afterward, atomically. +- Fallback to an unmodified managed base requires explicit user selection. + `extension restore GENERATION` validates the recorded base and exact inputs; it + does not reinterpret a historical package DB as matching a different base. +- Deployment prune respects booted, rollback, pending, pinned and success-gated + retention. Extension inputs/history and persistent data require separate cleanup. + +## 5. Output, errors and secrets + +Default output is human-readable. `--json` writes one final JSON result to stdout; +progress/logging uses stderr. `--events=jsonl` instead emits a documented event +stream ending in one terminal result. Never intermix raw child stdout with JSON. + +Result envelope: `apiVersion: archipelago.cli/v1`, `operation_id`, `operation`, +`state`, `changed`, `data`, `warnings`, `error`. Error includes stable `code`, +message, phase, implicated artifact/path and diagnostic reference. No password, +token/private-key content or secret-bearing argv appears in results/logs. + +| Exit | Meaning | +|---|---| +| 0 | Requested operation completed; may be an idempotent no-op or staged, not booted | +| 2 | Invalid syntax/schema/input (`E_INPUT`) | +| 3 | Unsupported capability/context/adapter (`E_UNSUPPORTED`) | +| 4 | Authentication, signature or integrity failure (`E_TRUST`) | +| 5 | Dependency/conflict/precondition violation (`E_CONFLICT`) | +| 6 | Concurrent operation (`E_BUSY`) | +| 7 | Artifact unavailable/network/storage failure (`E_UNAVAILABLE`) | +| 8 | Build/check/transaction failure (`E_EXECUTION`) | +| 130 | Cancelled; result records the last completed durable phase | + +Credentials come from protected interactive input, configured secret files/FDs or +Docker secret mounts. CLI inspection is non-root where data permissions allow it; +disk/deployment/account mutation requires root. Logs remain accessible only at the +intended scope. System-account deletion stays forbidden under D-029/D-060. + +## 6. Delivery and verification + +Current code is an experimental subset: ISO builder/install/firstboot/status, +test-marker overlay, package self-check and evolving Host Extensions. It lacks most +commands above. Approval establishes required coverage, not present functionality. + +Implement in dependency order: schemas/identity → lock/registry verification → +layer build/composition → host plan/stage/update → net install → release/pipeline/ +portal workflows. Publish a capability matrix per binary build. Shared errors and +JSON envelopes precede automation that consumes them. + +Acceptance: every advertised command has context/privilege/error tests; invalid +inputs never partially mutate state; lock/plan drift is detected; SIGINT/restart and +concurrent operations are exercised; repeated add before/after boot and rollback +preserve correct intent; failure keeps previous deployment/boot choice; net install +and updates use the same release lock. CLI coverage is checked separately from +backend implementation and public release readiness. diff --git a/rfc/RFC-0010-docker-build-and-distribution.md b/rfc/RFC-0010-docker-build-and-distribution.md new file mode 100644 index 0000000..bc0f32f --- /dev/null +++ b/rfc/RFC-0010-docker-build-and-distribution.md @@ -0,0 +1,250 @@ +# RFC-0010: Docker Build Pipeline and HTTP Distribution + +- **Status:** Accepted — D-068, 2026-11-04 +- **Version:** 0.1 +- **Date:** 2026-11-04 +- **Scope:** First infrastructure phase; topology, domains and credentials supplied later +- **Depends on:** Accepted RFC-0008/0009; D-043, D-045–D-052, D-063, D-066/D-067 + +## 1. First deliverable + +D-071 supplies the first [deployment binding](../spec/terra-infrastructure.md): +terra, source registries in git.fasoley.net/Archipelago, mirror integration plus +standalone files, and https://mirror.nw-sys.ru/archipelago/ for homepage/ISO/OSTree. +It also requests registry-backed CLI updates followed by PackageKit and desktop +frontend integration. These bindings do not waive release or trust requirements. + +D-068 accepts Docker Compose with host cron and separate build/validation/publication +roles; monthly immutable combined snapshots and daily pinned candidate builds; +HTTP/native OSTree distribution; complete artifact publication before atomic signed +channel updates; shared release identities for updates, net install and the portal; +purpose-separated OpenPGP keys and same-image promotion. Core x86_64 is the first +publication target after its release gates; KDE/GNOME require independent acceptance. +Deployment addresses, server bindings, keys, exact schedules/limits and verified +worker isolation remain follow-up work. Acceptance does not establish implementation +or approve the separate RFC-0011/D-069 package-action proposal. + +Docker Compose manages the initial build/distribution services. A cron-triggered +pipeline captures exact inputs, builds layers/images/ISO variants, validates them +and publishes eligible releases to an HTTP artifact registry and download portal. +The same registry serves installed-system updates and online installation. + +Docker packages infrastructure processes; OS layers/images remain native OSTree +artifacts, not Docker images. OCI image registries for builder containers are an +independent transport, pinned by digest. Kubernetes and a bespoke job daemon are not +required. Public release gates remain unchanged; until proven, artifacts are private +staging even if the pipeline and portal are functional. + +## 2. Components and boundaries + +| Component | Responsibility and writable state | +|---|---| +| Scheduler | Host cron invokes a versioned Compose/CLI entrypoint; durable schedule/run records | +| Build worker | Per-job Docker execution environment, Arch staging/nspawn, locked toolchain, scratch workspace/cache | +| Validation worker | QEMU/KVM boot/install/update tests, isolated VM disks and retained evidence | +| Publisher | Separate one-shot job with signing/publish credentials; immutable objects and atomic release pointers | +| HTTP registry | Read-only serving of package snapshots, native OSTree archive repositories, descriptors and releases | +| Portal | Generated static variant/download pages from authenticated release catalog | +| Snapshot adapter | Host-controlled ZFS capture/export of mirror data; no ZFS administration exposed to clients | + +Initial parallelism is one build/validation job per worker; increase only through +resource configuration. Workspaces, caches, jobs and published storage use dedicated +volumes. Download/registry/portal containers get no Docker socket, devices or build +write access. Cron uses the host Docker CLI; build jobs do not need Docker-in-Docker. + +Docker does not replace nspawn isolation or supply a systemd/cgroup setup magically. +The worker profile must provide private mount propagation, delegated cgroup v2, +required mount/loop capabilities and an explicit disposable Arch staging boundary. +KVM is passed only to validation workers. Exact device/capability/SELinux profile +must be tested on the selected deployment host before rollout. If nested nspawn +cannot meet that boundary, use a dedicated VM worker; do not silently run package +transactions on the infrastructure host. This is an explicit deployment gate. + +## 3. Pipeline profile and scheduling + +A proposed `PipelineProfile` contains logical `id`, SourceSet selector, snapshot +policy, enabled variant/architecture matrix, builder/validator OCI digests, build and +validation profile IDs, resource/time limits, retention policy, publication target, +and schedule `{cron, timezone, overlap, misfire}`. Physical URLs/paths/secret names +are deployment bindings, not hard-coded artifact identities. + +Proposed defaults for approval: UTC; daily candidate builds; monthly snapshot +capture; overlap `skip-and-record`; misfire `run-once-latest`; automatic publication +only to private staging initially. Exact cron expressions are configuration and +must be supplied before deployment. A cron tick never implicitly promotes stable. + +Host cron launches `docker compose run --rm worker archipelago pipeline run ...`. +A durable per-profile lock prevents overlap across manual/retry/cron invocation. +Each tick records scheduled time, actual start, SourceSet/lock IDs and final state. +Retries get a new attempt ID and reuse the same immutable inputs unless the operator +explicitly requests a new resolve. Network retries are bounded; failed runs leave +the prior release pointer intact. Missed ticks are not replayed as an unbounded queue. + +Run state machine: + +```text +queued → resolving → building-packages → sealing-snapshot → building-layers + → composing → building-installer → validating → candidate-ready + → publishing → published +any active phase → failed | cancelled +``` + +No timestamp/job ID is allowed to perturb deterministic artifact payload. Wall-clock +logs and evidence are separate from reproducible identity. A pipeline run may refer +to an already sealed snapshot and skip package capture/build/seal stages explicitly. + +## 4. Snapshot and pinning service + +D-073 defers capture and bulk mirror copying during experimental development; +use the live mirror with exact per-run input evidence and no silent substitution. +The release snapshot service below remains required before public release. +D-072 limits it to three retained monthly snapshots; reference-aware retirement +must precede a fourth capture, otherwise stop. See [terra binding](../spec/terra-infrastructure.md). + +Monthly package capture follows D-063. Freeze the mirror only after synchronization +finishes; capture repositories as one controlled transaction, then verify every +database-referenced package/checksum/signature exists in the read-only view. ZFS +snapshot atomicity alone does not prove repository semantic consistency. + +To avoid bootstrap cycles: + +1. Pin upstream repositories and package-build toolchain/source inputs. +2. Build the Archipelago package repository revision from those inputs. +3. Seal the combined ordered Arch + Archipelago Snapshot (RFC-0008). +4. Resolve layer locks against that single snapshot, then build layers. +5. Resolve CompositionLocks from the resulting exact layer commits. + +Never append packages to a sealed snapshot; create a new ID/revision. A monthly +human label may discover an ID, but clients persist the immutable ID. Exact archives, +DBs, signatures and catalog remain retrievable for every retained release and input +lock. A mirror/snapshot link must not resolve to mutable rolling package files. + +Pinning is a graph of SourceSet, Snapshot, LayerLock, layer artifact, CompositionLock, +image and installer identities. The registry stores these immutable descriptors; +the resolver creates locks, not a server that silently rewrites client pins. +“Latest” and channel aliases are discovery only. Missing locked artifacts are hard +errors; no fallback to newer packages. Retention marks the complete graph. + +## 5. HTTP registry contract + +Logical namespaces (base URLs will be supplied as deployment bindings): + +```text +/v1/blobs/sha256/ # canonical immutable documents/evidence +/v1/snapshots//... # descriptor, databases, indexes, packages +/v1/layers//descriptor.json +/v1/images//descriptor.json +/v1/installers//... # ISO, checksum, signature, descriptor +/v1/releases//manifest.json +/v1/channels///.json +/ostree/layers/... # native archive-mode OSTree repository +/ostree/images/... # native archive-mode OSTree repository +``` + +HTTP(S) GET/HEAD is sufficient for public consumers; Range/resume, Content-Length, +ETag and conditional reads are required for large artifacts. Immutable objects may +be cached permanently; mutable discovery pointers require revalidation. Digests and +signatures, not ETags, establish identity. Interrupted downloads use temporary files +and are exposed to consumers only after verification. Layer/image transport stays +compatible with ordinary OSTree pull/summary/ref verification. + +Publication is via the controlled publisher, not anonymous HTTP writes. Private +staging is a separately access-controlled namespace/origin; hiding links on the +portal is insufficient. It must not leak through public OSTree summaries or refs. +Public production endpoints use HTTPS; HTTP may be used behind the configured proxy +or in explicit private tests without replacing artifact verification. + +## 6. Trust and publication transaction + +Proposed initial trust profile: Arch package signatures retain pacman verification; +Archipelago OSTree commits and canonical metadata use detached OpenPGP signatures +with purpose-separated keys. Public-key fingerprints/policy arrive through a trusted +installer/configuration root, not from the same unsigned download being checked. +The existing experimental per-build pacman key is not this production key policy. +Publisher credentials and private keys are unavailable to package-build jobs. + +Signed channel documents contain channel/variant/architecture, monotonically +increasing sequence, release ID and expiry. Clients reject stale/replayed discovery +metadata relative to accepted sequence and trusted time; explicit historical release +selection/rollback remains possible without silently downgrading channel trust. +Key rotation uses an authenticated policy update and overlap; exact key custody, +backup and deployment credentials are supplied before infrastructure rollout. + +Publication per `(architecture, variant, channel)`: + +1. Upload objects, packages, locks, attestations, ISO and signed immutable release. +2. Verify the complete closure through the consumer HTTP path. +3. Under a publication lock, compare expected channel sequence and commit one new + signed channel document atomically. Never overwrite an immutable artifact ID. +4. Refresh native OSTree discovery refs/summary and portal catalog from that release. + +There is no cross-file HTTP atomicity. The signed channel document is the client +transaction boundary and references exact commits; clients do not combine a mutable +OSTree ref from one generation with a manifest from another. Native discovery can +temporarily lag; exact locked objects must already exist. Resume/retry reconciles +derived views without rebuilding artifacts or advancing sequence twice. + +Testing → stable promotion reuses the same verified image/installer identities and +attestations; it does not rebuild. D-050 requires full reproducibility and all +mandatory checks for both public channels. Failed gates never move their pointers. +RFC-0011 adds complete package-action coverage of the locked Core/KDE/GNOME +minimum sets. Publisher checks policy/lock-bound coverage and functional attestations; +cron cannot bypass this gate or treat unknown scriptlets as harmless warnings. +Withdraw removes discovery eligibility with an audited catalog update; retained +artifacts remain available for existing locks and recovery. + +## 7. Updates, net install and ISO portal + +Installed official systems discover a signed channel release, verify its snapshot, +image/lock and compatibility, pull the exact image, reapply all local extensions, +validate and stage. Custom compositions obtain exact layer artifacts and resolve a +whole compatible CompositionLock before compose. A layer registry is not an excuse +to merge independently “latest” layers during host update. + +Net install means an installer boots locally, discovers/selects a verified release +and fetches its exact image closure over HTTP. PXE/iPXE is a separate future boot +transport, not a prerequisite. Before destructive disk apply, the plan binds disk +identity, verified release/lock, required artifacts and storage/provisioning profiles. +Prefetch the installation closure before erase by default; inability to fetch or +verify must not erase the target. Interrupted writes use installer journal/resume. +Offline ISO bundles bind the same release/image identities; they are not a separate +unversioned source of packages. + +Portal entries come only from eligible release metadata and contain variant, +Purpose (or Core-only), architecture, channel, version/date, ISO type (offline/net), +size, SHA-256, signature, release ID, installation instructions and validation scope. +Links target immutable artifacts. A `latest.iso` alias may redirect but the page +exposes the exact identity. Planned/failed variants have no fake download button. + +Phase-one enabled variant is the demonstrated Core x86_64 profile. The matrix can +enable concrete GNOME/KDE/Server/IoT variants only after their own manifests and +inherited D-051/D-052 checks pass. The exact first additional variants are an approval +question, not an assertion of current implementation. Publication is atomic per +variant/channel; failure of one variant does not mislabel another as validated. + +## 8. Operations, retention and acceptance + +Persist run state, logs, lock graph, publication journal and validation evidence. +Expose last successful run per track, failures, durations, disk pressure, snapshot +age, channel sequence and missing-object checks. Portal rendering failure must not +corrupt registry content. Registry backup includes metadata, OSTree refs/objects, +snapshots and trust policy; signing-secret backup has a separate controlled process. + +Server GC marks all channel/current releases, explicitly retained historical +releases, active jobs, published locks and backup/recovery roots. Sweep only after +a configured grace interval and publication locking; preview the closure first. +Do not delete a retained snapshot's package files because a rolling mirror removed +them. Initial default: no automatic deletion of published release closures. +Client deployment/history retention remains governed separately by D-046. + +Before acceptance: demonstrate cron/manual deduplication, crash/retry at every +publication step, missing/tampered inputs, complete immutable HTTP closure, +same-commit promotion, offline and net installation, update plus extension failure +preservation, authenticated private staging, reproducibility evidence, portal link +consistency and restore from backup. Docker worker isolation and resource limits +must be proven on the target host, not inferred from a Compose file. + +Pending deployment inputs: domains/base URLs, hosts/volumes/ZFS dataset, cron times, +enabled variants, worker isolation profile and quotas, TLS/auth mechanism, trusted +key fingerprints/custody, source remotes and backup/retention destinations. They are +bindings to this contract; changes to semantic trust/publication rules need review. diff --git a/rfc/RFC-0011-package-actions-compatibility.md b/rfc/RFC-0011-package-actions-compatibility.md new file mode 100644 index 0000000..b827475 --- /dev/null +++ b/rfc/RFC-0011-package-actions-compatibility.md @@ -0,0 +1,171 @@ +# RFC-0011: Minimum Package-Action Compatibility + +- **Status:** Accepted — D-069, 2026-11-04 +- **Version:** 0.1 +- **Date:** 2026-11-04 +- **Scope:** Core/KDE/GNOME scriptlet and ALPM-hook coverage; CLI contract +- **Depends on:** RFC-0003–0010; D-027, D-058/D-059, D-066–D-068 + +## 1. Required compatibility floor + +D-069 accepts this minimum scope, shared policy/CLI and execution-result contract, +readiness gates and the linked phased implementation plan. Exact KDE/GNOME manifests +and supported snapshot transitions require separate agreement before claiming full +coverage. Acceptance does not establish implementation or desktop readiness. + +The user requests support, at minimum, for actions from Arch `base`, `linux` and +the package sets implementing KDE and GNOME Purpose variants. This is a product +obligation, not a best-effort allowlist. + +For every supported snapshot/architecture, mandatory coverage includes: + +1. `base`, `linux`, their complete runtime dependency closure, and all additional + Core integration packages, including `archipelago`. +2. Complete runtime closure of `purpose/desktop/kde` together with Core: selected + display manager, onboarding, session and essential integrations. +3. Equivalent closure of `purpose/desktop/gnome` together with Core. +4. Build-only dependencies and their actions in the relevant isolated build contexts; + these must not leak into runtime payload. + +Packages with no actions are explicitly recorded. Missing inspection cannot count +as coverage. Initial architecture is x86_64; others require independent inventories +and evidence. Core-only does not acquire desktop runtime dependencies. + +Exact desktop package sets and onboarding adapters are reviewed versioned manifests, +not mutable repository groups. Group expansion, if used during authoring, is recorded +against a snapshot and becomes explicit locked names/provider choices. Supporting +KDE/GNOME does not imply every optional Arch application. Essential desktop/setup +dependencies cannot be omitted merely to hide an unsupported action. + +## 2. Inventory + +Inspect both distinct mechanisms: + +- `.INSTALL` functions: pre/post install, pre/post upgrade, pre/post remove, including + invoked helpers, version conditions and other executable inputs. +- ALPM hooks from the transaction root and incoming packages: shadowing/overrides, + filename order, Depends, NeedsTargets, AbortOnFail, targets and pre/post timing. + +Use native libalpm transaction semantics. A new hook can affect old files; inspecting +only incoming archives is insufficient. Generic shell analysis cannot prove all +behavior. Classification is reviewed and bound to exact source/helper identities, +arguments, conditions and expected effects. One function can contain actions in +several lifecycles. Hash equality alone does not prove compatibility with a changed +helper, transaction or environment. + +## 3. PackageActionPolicy + +Proposed `kind: PackageActionPolicy`, `apiVersion: archipelago/v1`, uses RFC-0008 +canonicalization. LayerLock and CompositionLock bind its digest. + +| Field | Meaning | +|---|---| +| `scope` | Snapshot, architecture, profile manifest and resolved package-set digest | +| `sources` | Package archive, path/checksum, helper/executable identities | +| `actions[].id` | Logical action ID with explicit source/function/branch | +| `actions[].triggers` | Operations, version predicates and native hook conditions/targets | +| `actions[].classification` | `build-local`, `finalize`, `deploy`, `runtime`, justified `inapplicable` | +| `actions[].adapter` | Name/version, code and configuration digests; omitted only for inapplicable actions | +| `actions[].inputs/outputs` | Paths/resources and generated ownership; no implicit live-host outputs | +| `actions[].after` | Dependency graph and deterministic ordering | +| `actions[].network` | Explicit permission; finalization always `none` | +| `actions[].timeout_seconds` | Bounded execution and defined failure outcome | +| `actions[].required` | Mandatory when required by the selected feature; cannot be downgraded to pass a gate | +| `actions[].evidence` | Test definitions, expected effects, failures and retry behavior | +| `no_actions` | Inspected packages without scripts/hooks | + +Inapplicable requires a precise predicate and reason, e.g. a historical migration +unreachable for locked old/new versions. “Works in our VM” is not a classification. +Observed runs are separate attestations bound to policy/input/result IDs; log paths +and timestamps do not perturb the policy's semantic identity. + +Avoid an identity cycle: resolve the package set first and hash its package/provider +records independently of action policy. Policy scope binds that set, not the full +LayerLock that will contain the policy digest. Construct the final lock afterward; +execution attestations bind the completed lock and policy together. + +## 4. Execution + +Preserve native transaction/trigger semantics for valid staging actions. Package +scripts execute only in isolation. Deferred actions have explicit replacement +lifecycles and completion evidence. + +- Override only the exact reviewed ALPM hook and record its replacement. +- Mixed-phase scriptlets need reviewed package adaptations or execution adapters; + blanket `systemctl`/`useradd`/`ldconfig` no-op wrappers are not adapters. +- Managed recomposition selects payload and runs finalizers; it does not replay + every scriptlet as a pacman upgrade (D-026/D-027). +- Host Extensions use the same policy engine on base plus requested packages. + Unknown actions outside the floor fail with diagnostics and preserve state; + extending support adds policy and tests, not an ignore-unknown flag. +- Service start/restart never affects the builder or current deployment while + preparing another one. Preserve units and target sysusers/tmpfiles/defaults. +- Preserve existing target identities and administrator enablement; temporary + staging accounts are not shipped as merged machine account state. +- Required `/var` or `/opt` seed/migration behavior needs an explicit adapter and + update/rollback proof; discarding payload and reporting success is prohibited. + +Follow RFC-0005 ordering/placement for linker, schemas, GIO/loaders, MIME, icons, +trust, locales, hwdb and target-kernel depmod/initramfs. Mutable font caches, +accounts and machine identities belong to target lifecycle. DKMS is mandatory if +selected by a supported manifest, not for every external DKMS package in Arch. +Display manager, session and native onboarding must actually function. + +Required errors, timeouts, missing outputs and unexplained effects fail the +candidate even if pacman exits zero. Log regexes are diagnostics, not the complete +contract: instrument reviewed adapters and retain a result ledger while preserving +libalpm semantics. + +## 5. CLI + +All commands are under `archipelago`: + +| Command | Result / boundary | +|---|---| +| `hooks inventory --lock LOCK --output INVENTORY` | Inspect verified inputs without script execution; enumerate actions and no-action packages | +| `hooks explain ACTION --inventory INVENTORY` | Source, trigger, phase, adapter, constraints and evidence | +| `hooks validate --inventory INVENTORY --policy POLICY` | Validate identities, mappings, graph and outputs | +| `hooks coverage --lock LOCK --policy POLICY --json` | Coverage by package/profile/transaction scenario, with blocking action IDs | +| `hooks test --policy POLICY --case CASE --output DIR` | Isolated bounded tests and attestations; never live `/usr` | + +Policy authoring is explicit versioned review. There is no auto-approve shortcut. +Manifest validation, resolve, layer build, compose, update, extension add and release +verification consume one contract, not independent allowlists. + +States: `covered`, `inapplicable`, `unclassified`, `stale`, `missing`. Source/helper/ +trigger-context changes invalidate affected evidence. Reuse is explicit and only +where inputs and declared context match; unchanged package names are insufficient. + +Report profile/lock/policy IDs, counts, blocked IDs, missing adapters and affected +outputs. RFC-0009 error envelopes identify package/function/hook, snapshot and +required adapter work; disabling checks is not the normal installation remedy. + +## 6. Required scenarios and gate + +For every Core/KDE/GNOME candidate: + +1. Fresh isolated install/build and complete composition finalization. +2. Supported old → new snapshots, including version-gated upgrade branches. +3. Recomposition after layer/extension changes: removed inputs disappear from + aggregates without deleting persistent user/service data. +4. Removal scriptlets only where a workflow actually performs native removal; + otherwise explicitly inapplicable. Overlay removal remains recomposition. +5. Runtime accounts/directories, defaults/services, local login, desktop session, + display manager and declared first-user onboarding. +6. Injected PostTransaction failure with pacman exit zero, wrong helper digest, + timeout, missing output and attempted live-host effect. +7. Repeated runtime initialization and update/rollback preservation of IDs, data + and administrator configuration within D-036's scope. + +Gate: **zero unclassified/stale/missing mandatory actions**, plus passing required +functional evidence. A percentage alone cannot pass. This supplements D-051/D-052 +and reproducibility, replacing neither. Failed private runs may retain diagnostics +but are not usable/public testing candidates. Other public variants still obey D-050. + +## 7. Implementation and approval + +The minimum closures, policy/CLI contract, gates and +[implementation plan](../spec/package-actions-plan.md) are accepted by D-069. +Exact initial KDE/GNOME manifests and the supported transition matrix remain to be +agreed. Package-specific persistence, defaults and identity adaptations need reviewed +semantics and tests. Acceptance does not claim implemented desktop compatibility. diff --git a/ru/README.md b/ru/README.md index d675a15..ffc1998 100644 --- a/ru/README.md +++ b/ru/README.md @@ -1,5 +1,8 @@ # Archipelago — RFC v0 +**[Реестр принятых контрактов](spec/contract-registry.md)** — единая точка входа: +объём, решения, нормативные источники и открытые детали реализации D-001–D-074. + [English version](../README.md) **Статус:** Accepted — принятая архитектурная база (D-061)\ @@ -34,6 +37,29 @@ - [`examples/managed-overlay.yaml`](examples/managed-overlay.yaml) — иллюстративный манифест Managed Overlay. - [`examples/host-extensions.yaml`](examples/host-extensions.yaml) — иллюстративное локальное состояние Host Extensions. +## Контракты реализации и проекты + +- [Развёртывание на terra и desktop updates](spec/terra-infrastructure.md), D-071: + Git-реестры, mirror integration, standalone deploy и направление CLI/UI. + +- [Замороженный Layer YAML/JSON v1](../schemas/README.md), D-070; + [протокол поблочного утверждения](spec/layer-yaml-freeze.md). + +- [Русский обзор и вопросы согласования](spec/contracts-v1-review.md). +- [RFC-0008, EN](../rfc/RFC-0008-manifests-locks-and-artifacts.md): manifests, два lock-этапа, identities и package/layer artifacts. +- [RFC-0009, EN](../rfc/RFC-0009-cli-contract.md): полный каталог CLI и lifecycle операций. +- [RFC-0010, EN](../rfc/RFC-0010-docker-build-and-distribution.md): Docker/cron, HTTP registry, pinning, net install и ISO-портал. +- [RFC-0011](rfc/RFC-0011-package-actions-compatibility.md): обязательный минимум package actions Core/KDE/GNOME. +- [План реализации package actions](spec/package-actions-plan.md), [примеры v1](../examples/v1/README.md). + +Семантика RFC-0008 принята D-066 (2026-11-04); конкретные схемы/адаптеры ещё открыты. +Каталог CLI и lifecycle RFC-0009/D-067 приняты (2026-11-04), реализация поэтапная. +Инфраструктура/публикация RFC-0010/D-068 принята (2026-11-04); параметры деплоя +и проверка изоляции ещё требуются. RFC-0011/D-069 и план реализации приняты +(2026-11-04); точные desktop manifests, transition matrix и доказательства реализации +ещё требуются. D-061 относится только к RFC-0001–0007. +Полные новые RFC-0008–0010 пока на английском; русский обзор не подменяет их детали. + ## Значения статусов RFC - **Draft** — обсуждается. diff --git a/ru/rfc/RFC-0001-architecture.md b/ru/rfc/RFC-0001-architecture.md index debf343..1d41c8e 100644 --- a/ru/rfc/RFC-0001-architecture.md +++ b/ru/rfc/RFC-0001-architecture.md @@ -12,6 +12,9 @@ Archipelago — универсальный Linux-дистрибутив на б Он предоставляет декларативный способ сборки, публикации, установки, обновления, смены базы (rebase), отката и управления композициями ОС. Также он управляет выбранными рабочими нагрузками во время работы системы, сохраняя стандартные контракты файловой системы и исполнения Linux. +D-062 выбирает Rust для основного бинарника `archipelago` и функциональных модулей. Лабораторные +инструменты могут использовать другие языки; точные FFI/адаптеры остаются контрактами реализации. + Проект должен поддерживать три контекста исполнения через один основной CLI/бинарник `archipelago`: 1. **Хост сборки** — сборка пакетов, слоёв, композиций, релизов и артефактов установщика на поддерживаемом Linux-хосте. @@ -154,6 +157,12 @@ D-045/D-050 определяют публичные каналы образов Работает в live-среде. Подготавливает хранилище, инициализирует целевой репозиторий/deployment OSTree, устанавливает выбранный образ и настраивает загрузочную интеграцию. +D-064 включает управление установкой и первым запуском в live/installed контексты +единого бинарника. Поддерживать отложенное создание основного пользователя при первом +boot установленной ОС, терминальную настройку Core и штатные мастера GNOME/KDE, +где возможно. Интеграция frontend принадлежит конкретному Purpose. Daemon, стабильный +GUI API и профиль разделов этим не выбираются; границы аккаунтов — RFC-0006 §4.1. + ## 6. Контексты исполнения Бинарник `archipelago` должен предоставлять функции, соответствующие его контексту исполнения. diff --git a/ru/rfc/RFC-0002-layers-and-overlays.md b/ru/rfc/RFC-0002-layers-and-overlays.md index 2f6fc3c..d793eee 100644 --- a/ru/rfc/RFC-0002-layers-and-overlays.md +++ b/ru/rfc/RFC-0002-layers-and-overlays.md @@ -113,7 +113,10 @@ Host Extensions применяются поверх управляемой ко ## 4. Обязанности Arch Core -Core собирается из метапакета Arch Linux `base` и пакета ядра `linux`. Это начальная основа, а не исчерпывающий список: дополнительные firmware и входы загрузочной/deployment-интеграции ещё нужно определить. +Core собирается из метапакета Arch Linux `base` и пакета ядра `linux`. D-074 явно +добавляет `linux-firmware` со штатными зависимостями в Core и live installer, +без расчёта на косвенную зависимость от `linux`. Это не исчерпывающий список: +дополнительные hardware-specific firmware и boot/deployment inputs требуют review. Arch Core предоставляет универсальную основу Linux, включая: diff --git a/ru/rfc/RFC-0003-build-and-composition.md b/ru/rfc/RFC-0003-build-and-composition.md index f2f3d24..b2faa8e 100644 --- a/ru/rfc/RFC-0003-build-and-composition.md +++ b/ru/rfc/RFC-0003-build-and-composition.md @@ -47,6 +47,11 @@ Snapshot определяет доступное множество пакето ### Выбор пакетов +D-063 предусматривает ежемесячные snapshots репозиториев; их создание через ZFS +на хосте зеркала отложено до рабочего экспериментального `archipelago-core-latest.iso`. +Этот порядок реализации не ослабляет идентичность D-043 и публичные условия D-050. +Имя экспериментального файла latest не является идентичностью snapshot или публичным релизом. + Обычный процесс: 1. Разрешить пакет из закреплённого бинарного репозитория. 2. Проверить идентичность и целостность пакета. diff --git a/ru/rfc/RFC-0006-system-accounts.md b/ru/rfc/RFC-0006-system-accounts.md index e3740d5..3916a9f 100644 --- a/ru/rfc/RFC-0006-system-accounts.md +++ b/ru/rfc/RFC-0006-system-accounts.md @@ -77,6 +77,21 @@ D-060 уточняет: запрет касается постоянных за D-036 снимает универсальную непрерывность актуальных аккаунтов/credentials как блокер MVP. Точная начальная подготовка, инструкции восстановления и тесты прерванных переходов ещё нужны в рамках штатной модели OSTree. +### 4.1 Отложенная настройка первого запуска (D-064) + +Установка может откладывать создание основного пользователя до onboarding в первом +загруженном deployment. Завершить его до подготовки последующих обычных целей отката +(D-036). Core предоставляет терминальный CLI; GNOME/KDE Purpose по возможности +переиспользуют штатные мастера. Создание нового пользователя происходит до первого +обычного входа; последующие welcome/customization пользователя — другой lifecycle. + +Использовать стандартные механизмы аккаунтов и deployment-local `/etc`. Интеграция +GUI/CLI сохраняет существующие идентичности и допускает повтор прерванного provisioning. +Добавление desktop Purpose к настроенному Core сохраняет основного пользователя. +Выбор frontend, доказательство завершения, протокол повтора, привилегии setup-сеанса +и порядок systemd остаются контрактами реализации. Общий маркер завершения в `/var` +сам по себе не доказывает наличие нужного аккаунта в `/etc` загруженного deployment. + ## 5. Критерии приёмки - Первая загрузка создаёт объявленные служебные идентичности до запуска зависимых служб. @@ -90,6 +105,9 @@ D-036 снимает универсальную непрерывность ак - Базы аккаунтов независимых сборок не сливаются в состояние хоста. - Update и оба пути rollback проверяются на видимость аккаунтов, пользовательский вход, credentials и владение общими данными по явно выбранной политике переходов; после D-032 безусловная непрерывность идентичностей не предполагается. - Прерванное создание допускает повтор без дублирования идентичностей или потери данных. +- Отложенный onboarding создаёт пригодного для входа основного пользователя до + последующих deployments; завершённая настройка не повторяется при обычном reboot + или добавлении Purpose. ## 6. Открытые вопросы реализации diff --git a/ru/rfc/RFC-0007-ostree-platform-integration.md b/ru/rfc/RFC-0007-ostree-platform-integration.md index 7927723..7e223cb 100644 --- a/ru/rfc/RFC-0007-ostree-platform-integration.md +++ b/ru/rfc/RFC-0007-ostree-platform-integration.md @@ -90,6 +90,12 @@ D-036 ограничивает начальный UX обычным single-user ## 6. Загрузка и активация +D-065 выбирает экспериментальный установочный профиль x86_64 UEFI VM с GPT, +FAT32 ESP и ext4 root, systemd-boot, без шифрования и Secure Boot. При необходимости +интеграции допускается отдельный `/boot`. До заявления работоспособности проверить +полную установку из live ISO и загрузку с диска; экспериментальный выбор не фиксирует +все контракты разделов/артефактов и не заменяет публичные release gates. + Начальный загрузчик — systemd-boot (UEFI). GRUB 2 не является обязательным начальным backend. Нужно переиспользовать штатные механизмы deployment OSTree и BLS, проверяя реальное обнаружение/выбор boot entries systemd-boot, а не предполагая его. Текущий пакет OSTree в Arch уже поставляет: diff --git a/ru/rfc/RFC-0011-package-actions-compatibility.md b/ru/rfc/RFC-0011-package-actions-compatibility.md new file mode 100644 index 0000000..879215e --- /dev/null +++ b/ru/rfc/RFC-0011-package-actions-compatibility.md @@ -0,0 +1,163 @@ +# RFC-0011: Минимальная совместимость пакетных действий + +- **Статус:** Accepted — D-069, 2026-11-04 +- **Версия:** 0.1 +- **Дата:** 2026-11-04 +- **Охват:** hooks/scriptlets Core/KDE/GNOME и контракт CLI +- **Основа:** RFC-0003–0010, D-027, D-058/D-059, D-066–D-068 +- [English](../../rfc/RFC-0011-package-actions-compatibility.md) + +## 1. Обязательный минимум + +D-069 утверждает минимум, общий policy/CLI и контракт результатов исполнения, +критерии готовности и связанный поэтапный план. Точные KDE/GNOME manifests и +поддерживаемые переходы snapshots согласуются отдельно до заявления полного +покрытия. Утверждение не подтверждает реализацию или готовность desktop. + +По предложению пользователя минимум поддержки включает действия Arch `base`, +`linux` и наборов, реализующих KDE/GNOME Purpose. Это обязательство продукта, +а не best-effort список разрешённых скриптов. + +Для каждого поддерживаемого snapshot/architecture покрываются: + +1. `base`, `linux`, полный runtime dependency closure и интеграционные пакеты Core, + включая `archipelago`. +2. Полный runtime closure `purpose/desktop/kde` вместе с Core: выбранные DM, + onboarding, session и необходимые интеграции. +3. Аналогичный набор `purpose/desktop/gnome` вместе с Core. +4. Build-only зависимости и действия в соответствующих изолированных сборках; + их нельзя случайно переносить в runtime payload. + +Пакеты без действий явно учитываются: отсутствие инвентаризации не означает покрытие. +Первая архитектура — x86_64; другим нужны собственные inventory/evidence. +Core-only не получает desktop-зависимости на целевой машине. + +Точные desktop-наборы и onboarding adapters — согласуемые версионированные манифесты. +Если для составления списка используется группа пакетов, её раскрытие фиксируется +на snapshot, после чего имена и выбор providers закрепляются явно. Не требуется +весь каталог необязательных приложений Arch; исключать необходимый компонент +desktop/setup ради сокрытия его неподдерживаемого действия нельзя. + +## 2. Инвентаризация + +Учитываются оба механизма: + +- `.INSTALL`: pre/post install, pre/post upgrade, pre/post remove, вызываемые + helpers, условия версий и другие исполняемые входы. +- ALPM hooks из transaction root и входящих пакетов: overrides/shadowing, + порядок файлов, Depends, NeedsTargets, AbortOnFail, targets и pre/post фазы. + +Используется штатная семантика libalpm. Новый hook способен затронуть старые файлы, +поэтому проверки только входящих архивов недостаточно. Общий анализ shell не +доказывает все эффекты: нужна рецензируемая классификация точных исходников/helpers, +условий, аргументов и ожидаемых результатов. Одна функция может содержать действия +нескольких lifecycle-фаз. Равенство hash не доказывает совместимость с новым helper. + +## 3. PackageActionPolicy + +Предлагается `kind: PackageActionPolicy`, `apiVersion: archipelago/v1`, канонизация +RFC-0008. LayerLock/CompositionLock закрепляют digest policy. + +| Поле | Содержание | +|---|---| +| `scope` | Snapshot, architecture, manifest и digest разрешённого package set | +| `sources` | Archive identity, путь/checksum, helper/executable identities | +| `actions[].id` | Логический ID и явные source/function/branch | +| `actions[].triggers` | Операции, условия версий и штатные условия/targets hooks | +| `actions[].classification` | `build-local`, `finalize`, `deploy`, `runtime`, обоснованное `inapplicable` | +| `actions[].adapter` | Имя/версия, code/config digests; отсутствует только у inapplicable | +| `actions[].inputs/outputs` | Пути, ресурсы и происхождение generated outputs | +| `actions[].after` | Зависимости и детерминированный порядок | +| `actions[].network` | Явное разрешение; finalization всегда `none` | +| `actions[].timeout_seconds` | Ограниченное время и определённый исход ошибки | +| `actions[].required` | Обязательно, если нужно выбранной функции; нельзя понизить ради gate | +| `actions[].evidence` | Определения тестов, ожидаемые эффекты, ошибки и retry | +| `no_actions` | Проверенные пакеты без scripts/hooks | + +Inapplicable требует точного условия и причины, например недостижимой исторической +миграции для закреплённых old/new versions. «Работает в VM» — не классификация. +Результаты запусков — отдельные attestations с policy/input/result IDs; время и пути +логов не меняют семантический digest policy. + +Цикла идентичностей нет: сначала разрешается package set и хешируются его packages/ +providers независимо от policy. Scope policy ссылается на этот набор, а не на полный +LayerLock, содержащий digest самой policy. Затем создаётся окончательный lock; +execution attestations связывают готовые lock и policy. + +## 4. Исполнение + +Сохраняются штатные транзакции и triggers для действий, допустимых в staging. +Скрипты выполняются только в изоляции. Перенос в другие фазы имеет явную замену +и доказательство завершения. + +- Override отключает только точный проверенный hook и указывает замену. +- Mixed-phase scriptlets требуют адаптации пакета или execution adapter; + тотальные no-op wrappers для systemctl/useradd/ldconfig недопустимы. +- Managed composition выбирает payload и запускает finalizers, не переигрывает + все scriptlets как pacman upgrade. +- Host Extensions используют тот же policy engine; неизвестные действия вне + минимума завершаются диагностикой без изменения deployment. Поддержка расширяется + policy/tests, а не флагом ignore-unknown. +- Сервисы не запускаются на builder/current host при подготовке другого deployment. + Сохраняются units, sysusers/tmpfiles и объявленные target defaults. +- Сохраняются существующие identities и пользовательское enablement; staging + accounts не становятся объединённой машинной базой пользователей. +- Необходимые `/var`/`/opt` seeds/migrations требуют адаптера и update/rollback + проверки. Отбросить payload и объявить успех нельзя. + +Порядок/размещение caches и kernel outputs — по RFC-0005: linker, schemas, +GIO/loaders, MIME/icons/trust/locales/hwdb, depmod перед initramfs целевого ядра. +Font cache, accounts и machine identities — target lifecycle. DKMS обязателен, +если включён поддерживаемым манифестом; это не обещание всех внешних DKMS пакетов. +DM, session и native onboarding должны действительно работать. + +Ошибка, timeout, отсутствие output или необъяснённый эффект обязательного действия +отклоняют candidate даже при exit pacman=0. Regex логов — диагностика, не полный +контракт: нужен ledger результатов проверенных адаптеров со штатной семантикой ALPM. + +## 5. CLI + +Команды `archipelago hooks`: + +| Команда | Назначение | +|---|---| +| `inventory --lock LOCK --output INVENTORY` | Инспекция проверенных входов без исполнения скриптов | +| `explain ACTION --inventory INVENTORY` | Source/trigger/phase/adapter/evidence | +| `validate --inventory INVENTORY --policy POLICY` | Проверка identities, mappings, DAG и outputs | +| `coverage --lock LOCK --policy POLICY --json` | Покрытие по пакетам, профилям и сценариям, blocking IDs | +| `test --policy POLICY --case CASE --output DIR` | Изолированные ограниченные тесты и attestations | + +Policy оформляется версионированным review, без auto-approve. Manifest validation, +resolve, build, compose, update, extension add и release verify используют один +контракт, а не независимые allowlists. + +Состояния: covered/inapplicable/unclassified/stale/missing. Изменения source/helper/ +trigger context инвалидируют затронутое evidence. Повторное использование явно +фиксируется при совпадении входов/контекста; одного имени пакета недостаточно. +Отчёт содержит profile/lock/policy IDs, counts, blocking IDs, missing adapters и +outputs. Ошибки RFC-0009 указывают пакет/function/hook, snapshot и необходимую работу. + +## 6. Сценарии и gate + +Для Core/KDE/GNOME нужны fresh install/build/finalization, поддерживаемые переходы +snapshots и version branches, recomposition/removal с обновлением aggregate outputs, +runtime initialization и реальный login/session/onboarding. Removal scriptlets +выполняются только в реально использующих ALPM removal workflows; для остальных +нужно обоснованное inapplicable, а не имитация removal при удалении overlay. + +Fault injection: PostTransaction failure при exit pacman=0, wrong helper digest, +timeout, missing output и попытка live-host effect. Runtime retry/update/rollback +сохраняют IDs, данные и administrator configuration в границах D-036. + +Gate: **ноль unclassified/stale/missing обязательных действий** плюс успешные +обязательные функциональные проверки. Процент покрытия сам по себе недостаточен. +Это дополнение к D-051/D-052 и воспроизводимости, не замена. Неуспешный private run +сохраняет диагностику, но не считается пригодным candidate/public testing release. + +## 7. Реализация и утверждение + +Минимум, policy/CLI, критерии готовности и +[план](../spec/package-actions-plan.md) приняты D-069. Конкретные desktop manifests +и transition matrix ещё требуют согласования. Package-specific persistence, +defaults и identity adapters требуют review и тестов. Поддержка desktop этим текстом +не объявляется. diff --git a/ru/spec/contract-registry.md b/ru/spec/contract-registry.md new file mode 100644 index 0000000..02e7370 --- /dev/null +++ b/ru/spec/contract-registry.md @@ -0,0 +1,90 @@ +# Реестр принятых контрактов + +[English](../../spec/contract-registry.md) + +**Срез: 2026-11-05. Охват: D-001–D-074, RFC-0001–0011.** +Это единая точка входа в принятые контракты. `C-xxx` — стабильные навигационные +идентификаторы; `D-xxx` остаются идентификаторами утверждения и истории решений. +Все записи ниже имеют статус **Accepted** в явно указанном объёме. Принятый +контракт, замороженный формат и проверенная реализация — разные состояния. + +## Источники и трактовка + +- [Журнал решений](decision-log.md) фиксирует утверждения и уточнения. Нормативные + требования находятся в соответствующих RFC и явно замороженных схемах. +- [Открытые вопросы](open-questions.md) сохраняют детали, которые ещё не согласованы. + Утверждение архитектуры не замораживает все упомянутые примеры, форматы и адаптеры. +- D-061 утверждает RFC-0001–0007 с D-020–D-060. D-066–D-069 принимают последующие + контракты реализации; D-070 замораживает именно авторский формат Layer. +- Исторические формулировки читаются с уточнениями: D-055 меняет D-041 на ноль/один + Purpose; D-056 делает fallback D-017 явным и весь набор атомарным; D-057 исключает + recovery из статуса поддержки; D-049 запрещает автоматический rollback; + D-036 ограничивает account continuity D-032; D-060 сохраняет штатный DynamicUser. +- Противоречия документов требуют явного разрешения. Реестр сам по себе не заменяет + RFC, не принимает новые решения и не закрывает открытые вопросы. + +## Принятые контракты + +| ID | Контракт и принятый объём | Решения | Нормативный источник | Что ещё требуется | +|---|---|---|---|---| +| C-001 | Границы платформы: штатные объекты/commits/refs/transport/deployments OSTree, существующие Linux-инструменты, обычные filesystem/ELF contracts, OSTree из закреплённого Arch snapshot. Семантическая композиция принадлежит Archipelago. | D-001, D-002, D-013, D-035 | [RFC-0001](../rfc/RFC-0001-architecture.md), [RFC-0003](../rfc/RFC-0003-build-and-composition.md), [RFC-0007](../rfc/RFC-0007-ostree-platform-integration.md) | Доказательство работы конкретных адаптеров и опциональных возможностей OSTree. | +| C-002 | Независимая сборка неизменяемых слоёв, Core от base + linux, один полный image commit. Единственный эффективный владелец пакета, детерминированное переназначение общих зависимостей, пакетные payload и индекс внутри layer commits. | D-003, D-004, D-020, D-021, D-022, D-024, D-025, D-026, D-044 | [RFC-0002](../rfc/RFC-0002-layers-and-overlays.md), [RFC-0003](../rfc/RFC-0003-build-and-composition.md), [RFC-0008, EN](../../rfc/RFC-0008-manifests-locks-and-artifacts.md) | Полные индексы артефактов, реализация effective DB и conformance fixtures. | +| C-003 | Один Core, ноль/один Purpose; роли Desktop/Server/IoT и конкретные варианты. Официальный Core-only поддерживается; самописные overlays не получают поддержку автоматически. Аппаратные адаптации — overlays/profiles, без отдельного Hardware Layer. Смена Purpose сохраняет данные. | D-007, D-008, D-009, D-041, D-055 | [RFC-0002](../rfc/RFC-0002-layers-and-overlays.md), [RFC-0008, EN](../../rfc/RFC-0008-manifests-locks-and-artifacts.md) | Точные desktop-наборы, службы, DM и native onboarding adapters. | +| C-004 | Явный порядок overlays и проверка совместимости, без автодобавления/перестановки. Ограниченные overrides файлов/типов/метаданных с владельцем и provenance. Замена целого пакета — отдельная операция. Неограниченный overwrite и самостоятельное удаление нижних пакетов исключены. | D-010, D-038, D-039, D-040, D-054 | [RFC-0002](../rfc/RFC-0002-layers-and-overlays.md), [RFC-0008, EN](../../rfc/RFC-0008-manifests-locks-and-artifacts.md) | Реализация проверок, преобразований effective records и filesystem fixtures. | +| C-005 | Исходники в Git, manifest намерения отдельно от точных locks, один immutable ordered Arch + Archipelago snapshot на композицию. Content identities/checksums/provenance; дата и URL не идентичность; build не обновляет входы молча. | D-005, D-023, D-042, D-043 | [RFC-0003](../rfc/RFC-0003-build-and-composition.md), [RFC-0008, EN](../../rfc/RFC-0008-manifests-locks-and-artifacts.md) | Исполняемые схемы Snapshot/SourceSet/locks и полная проверка канонизации. | +| C-006 | Предпочтение бинарных пакетов, изолированные сборки. DKMS привязан к целевому kernel/ABI. Классификация hooks/scriptlets по build/finalize/deploy/runtime, явные замены перенесённых действий, offline-финализация, depmod перед initramfs. Обязательные ошибки блокируют публикацию даже при exit pacman=0. | D-011, D-012, D-027, D-058, D-059 | [RFC-0003](../rfc/RFC-0003-build-and-composition.md), [RFC-0005](../rfc/RFC-0005-hooks-and-finalization.md) | Snapshot-specific adapters, ABI-алгоритм и execution/output evidence. | +| C-007 | Host Extensions пересобираются из базы и полного requested set: имена из snapshot или сохранённые локальные архивы, согласованная package DB и история поколений. Нет live-мутаций /usr. Повторное применение атомарно; ошибка сохраняет deployments/входы; fallback только явно. | D-014, D-017, D-018, D-037, D-056 | [RFC-0004](../rfc/RFC-0004-host-extensions.md), [RFC-0009, EN](../../rfc/RFC-0009-cli-contract.md) | Стабильные generation/request formats, полные update/remove/restore workflows и покрытие пакетных действий. | +| C-008 | Поддержка описывает загруженный deployment и фактические изменения. Применённые extensions означают unsupported; pending/desired отдельно. Нет статуса recovery и гарантии совместимости любого локального пакета. | D-015, D-016, D-057 | [RFC-0004](../rfc/RFC-0004-host-extensions.md) | Полная диагностика и обнаружение изменений вне штатного управления. | +| C-009 | Данные сохраняются при update/rebase/rollback/смене Purpose. Один stateroot archipelago, Silverblue-style persistence в /var, штатные deployment-local /etc и merge /usr/etc. | D-019, D-030, D-032 | [RFC-0007](../rfc/RFC-0007-ostree-platform-integration.md) | Persistence/migration adapters, прежде всего /opt; глобальная синхронизация accounts не подразумевается. | +| C-010 | Стандартные sysusers/tmpfiles, сохранение UID/GID, без слияния build account DB. Удаляются только явно классифицированные human accounts; system/неоднозначные identities не удаляются. DynamicUser штатный. Первичный пользователь создаётся до следующих deployments; rollback edge case оговорён. | D-028, D-029, D-036, D-060 | [RFC-0006](../rfc/RFC-0006-system-accounts.md), [RFC-0007](../rfc/RFC-0007-ostree-platform-integration.md) | Надёжная классификация аккаунтов и конкретные reconciliation adapters. | +| C-011 | Pacman-format DB принадлежит образу и расположена нестандартно; live-мутации блокируются. Рабочие/history DB extensions сохраняются с привязкой к базе независимо от deployments. | D-031 | [RFC-0007](../rfc/RFC-0007-ostree-platform-integration.md), [RFC-0008, EN](../../rfc/RFC-0008-manifests-locks-and-artifacts.md) | Стабильные пути и полностью проверенные DB/live-guard adapters. | +| C-012 | systemd-boot и staged deployments; сохранение booted/rollback/pending/pinned. Ограниченные boot checks разрешают cleanup только после успеха. Службы запускаются в target lifecycle. Rollback явный, reboot отдельно; отказ не переключает загрузку автоматически. | D-033, D-034, D-046, D-047, D-048, D-049 | [RFC-0007](../rfc/RFC-0007-ostree-platform-integration.md), [RFC-0009, EN](../../rfc/RFC-0009-cli-contract.md) | Общие boot/storage profiles, success records, shutdown-диагностика и retention implementation. | +| C-013 | testing/stable продвигают тот же проверенный image без пересборки. Оба требуют полной воспроизводимости и функциональных gates. Core boot/login/extensions/overlays проверяются на каждом Purpose candidate, затем его службы/session. Эксперименты — закрытый staging. | D-045, D-050, D-051, D-052 | [RFC-0003](../rfc/RFC-0003-build-and-composition.md), [RFC-0010, EN](../../rfc/RFC-0010-docker-build-and-distribution.md) | Доказательство воспроизводимости, полная validation matrix и достоверные release attestations. | +| C-014 | Реестры входят в начальную архитектуру. Docker Compose + host cron, отдельные builder/KVM validator/publisher, monthly combined snapshots и daily pinned candidates. HTTP/native OSTree, атомарный подписанный канал после проверки всех артефактов; общие identities update/net install/портала; разделённые OpenPGP keys. | D-006, D-063, D-068 | [RFC-0001](../rfc/RFC-0001-architecture.md), [RFC-0010, EN](../../rfc/RFC-0010-docker-build-and-distribution.md) | Топология/URL, хранение ключей, точные расписания/квоты и проверка изоляции workers. | +| C-015 | RFC v0 утверждён; сначала сквозной профиль без сужения архитектуры и ослабления public gates. Основной бинарник и функциональные модули — Rust. | D-053, D-061, D-062 | [RFC-0001](../rfc/RFC-0001-architecture.md), [журнал](decision-log.md) | Этап реализации не означает полноты функциональности или заморозки module APIs. | +| C-016 | Control layer установки/first-run: live готовит диск/deployment, пользователя можно создать на первом installed boot. Core CLI, native desktop setup где возможно. Экспериментальный x86_64 UEFI VM: GPT, FAT32 ESP, ext4 root, systemd-boot, без encryption/Secure Boot. | D-064, D-065 | [RFC-0006](../rfc/RFC-0006-system-accounts.md), [RFC-0007](../rfc/RFC-0007-ostree-platform-integration.md) | Общие installer schemas, native desktop adapters и другие hardware/storage profiles. | +| C-017 | Строгие YAML/JSON manifests, канонические JSON/SHA-256 identities, отдельные LayerLock/CompositionLock, per-package OSTree payload и original/effective ALPM records с происхождением преобразований. | D-066 | [RFC-0008, EN](../../rfc/RFC-0008-manifests-locks-and-artifacts.md) | Авторский Layer заморожен C-020; остальные lock/artifact schemas, канонизация и DB adapters требуют проверки. | +| C-018 | Единый CLI builder/host/live: полный каталог, capabilities, проверяемый plan/apply под блокировкой, JSON/errors, журнал операций, отмена/resume с учётом стадии, desired/pending/booted; initially без обязательного daemon. | D-067 | [RFC-0009, EN](../../rfc/RFC-0009-cli-contract.md) | Поэтапная реализация команд/backends; принятый каталог не равен capabilities текущего бинарника. | +| C-019 | Обязательное покрытие действий base/linux/Core и полных KDE/GNOME runtime/build-наборов; учёт пакетов без действий. Общие policy/ledger/adapters и hooks CLI, ноль unresolved mandatory actions плюс функциональные проверки. Поэтапный план принят. | D-069 | [RFC-0011](../rfc/RFC-0011-package-actions-compatibility.md), [план](package-actions-plan.md) | Точные desktop manifests, поддерживаемые snapshot transitions и полное execution evidence. | +| C-020 | **Замороженный Layer YAML/JSON v1**: каркас Core/Purpose/Overlay, packages, runtime/provisioner inheritance, checks, actions, files, bounded overrides, compatibility/replacements, kernel/ABI references и строгая валидация. Изменения требуют согласования и версии схемы. | D-070 | [Схема](../../schemas/layer-v1.schema.json), [валидация](../../schemas/README.md), [протокол](layer-yaml-freeze.md) | Production Rust parser, полная семантическая проверка, ABI-алгоритм и desktop-наборы; Composition/lock/artifact formats этим решением не заморожены. | + +### C-021 — Развёртывание на terra и desktop updates + +**Accepted: D-071.** [Параметры развёртывания](terra-infrastructure.md): Git-реестры +YAML Core/Purpose и инфраструктуры в git.fasoley.net/Archipelago; builders, validators, +registry и портал на terra рядом с `/opt/mirror`, обязательны standalone-файлы. +База homepage/ISO/OSTree — `https://mirror.nw-sys.ru/archipelago/`. Точные YAML revisions +и закреплённые входы, композиция из layer commits registry, затем ISO. Material You +и явная независимость от Arch Linux. Сначала registry-backed CLI update, затем +PackageKit/GNOME Software/KDE Discover. +Открыты lock/release schemas, хранение ключей, изоляция workers, реализация pipeline +и обновлений и их проверки. Public gates C-013/C-014 сохраняются. + +**Уточнения D-072/D-073:** отдельный `tank/archipelago`, не более трёх месячных +snapshots с сохранением нужных release/lock inputs; capture и полное копирование +отложены для экспериментальных сборок из живого зеркала. Per-run evidence обязателен. + +### C-022 — Ежедневный экспериментальный Core и firmware + +**Accepted: D-074.** Ежедневные Core candidates из текущих исходников и live mirror +для проверки инфраструктуры и обновлений по image commit. Явный `linux-firmware` +в Core и live installer со штатными зависимостями. Public gates сохраняются; +воспроизводимость, update success и поддержка оборудования проверяются отдельно. + +## Реализация и доказательства + +Статус реализации независим от принятия контракта. Источники фактических результатов +в рабочем пространстве: `test-lab/CORE-ISO-RESULTS.md`, `system/EXTENSIONS.md`, +`builder/HOOK-REVIEW.md`, `installer/CONTROL-LAYER.md`, `manifests/CORE-EXPERIMENT.md`. +Для заявления соответствия проверяй конкретные run/commit/input identities. +Schema fixtures, успешный экспериментальный ISO или один DKMS-модуль не доказывают +полное desktop-покрытие, поддержку всего оборудования или допуск к public release. + +## Ведение реестра + +При явном принятии или уточнении контракта синхронизируются RFC/схема, журнал решений, +этот реестр EN/RU, открытые вопросы и примеры. C IDs сохраняются; замена или уточнение +получает ссылку на решение, история не стирается. Новые предложения остаются в draft/ +review до утверждения. Новому самостоятельному контракту добавляется строка; +уточнение отражается в существующей. Все принятые D-001–D-074 представлены хотя бы +раз; пересечения намеренны. Само индексирование не создаёт нового решения архитектуры. diff --git a/ru/spec/contracts-v1-review.md b/ru/spec/contracts-v1-review.md new file mode 100644 index 0000000..4d14835 --- /dev/null +++ b/ru/spec/contracts-v1-review.md @@ -0,0 +1,122 @@ +# Пакет контрактов: манифесты, CLI и инфраструктура + +**Статус: утверждён. Дата: 2026-11-04.** D-066–D-069 и план package actions приняты. +Полный архитектурный охват собран в [реестре контрактов](contract-registry.md). +Точные desktop manifests и матрица переходов snapshots ещё согласуются. +Авторская схема Layer затем заморожена D-070: [схема](../../schemas/README.md). +Схемы Composition/locks/artifacts остаются отдельной работой. +Инфраструктура/публикация RFC-0010 принята; параметры +развёртывания и проверка изоляции workers ещё требуются. Приняты каталог CLI и lifecycle RFC-0009 +с поэтапной реализацией, а также семантика RFC-0008 в объёме D-066; +конкретные схемы, адаптеры и доказательство реализации ещё требуются. + +Это русский обзор пакета. Полные проекты RFC-0008–0010 пока ведутся на английском; +для RFC-0011 также подготовлена русская версия. Принятая база RFC-0001–0007 неизменна. + +## 1. Манифесты и pinning — D-066 + +[RFC-0008](../../rfc/RFC-0008-manifests-locks-and-artifacts.md), принято D-066: + +- Строгий YAML 1.2/JSON с зарезервированным `apiVersion: archipelago/v1`. + Неизвестные поля, дубликаты ключей и неявные преобразования — ошибки. +- Типы Layer: Core, Purpose, Overlay; одна архитектура, пакеты runtime/build, + совместимость, файлы, ограниченные overrides, actions и runtime-декларации. +- Composition: один Core, ноль/один Purpose, упорядоченные overlays, один snapshot, + boot/validation/installer profiles. Порядок не исправляется молча. +- Канонический JSON RFC 8785 и SHA-256; URL — транспорт, не идентичность. +- `LayerLock` закрепляет исходники, пакеты, среду и адаптеры сборки слоя. + `CompositionLock` закрепляет уже собранные commits, владение, финализацию и boot. +- Внутри layer commit — отдельные пакетные payload и собственные файлы слоя, + индекс объектов, исходные ALPM records и provenance. Композиция берёт payload + из OSTree commits, а не повторно ставит managed-пакеты из репозитория. +- Итоговая ALPM DB описывает эффективное дерево; каждое отклонение от исходных + пакетных records имеет явную трансформацию. Оригинальные сведения сохраняются. + Это существенный новый контракт, требующий отдельных интеграционных fixtures. + +Примеры: [v1](../../examples/v1/README.md). Это review-fixtures, не рабочий GNOME +профиль и не объявление поддерживаемого v1 API текущим бинарником. + +## 2. Полнота CLI — D-067 + +[RFC-0009](../../rfc/RFC-0009-cli-contract.md) задаёт полный каталог: + +- Манифесты, resolve/locks, snapshots, hooks, package/layer/image/ISO builds. +- Pipeline, registry, release/promotion и генерация портала. +- Status/verify/diff, update/rebase, Purpose, ordered overlays. +- Extensions add/remove/history/restore и отдельные package overrides. +- Deployments, pinning/retention, явный rollback, install plan/apply/resume. +- Firstboot, provisioning и управление явно классифицированными human accounts. + +Общие правила: capability matrix, единые JSON/errors, проверяемый plan ID, +повторная проверка preconditions под блокировкой, журнал операции, отмена/возобновление, +раздельные desired/pending/booted. Нет автоматического reboot или fallback. +Команда, ещё отсутствующая в бинарнике, возвращает unsupported, а не фиктивный успех. +Сначала — CLI без обязательного daemon; workload managers выбираются отдельно. + +## 3. Docker-инфраструктура — D-068 + +[RFC-0010](../../rfc/RFC-0010-docker-build-and-distribution.md), принято D-068: + +1. Docker Compose; host cron запускает версионированный pipeline entrypoint. +2. Отдельные build worker, KVM validator и publisher с ключами публикации. +3. Ежемесячный snapshot зеркала с проверкой всех DB/package/checksum/signature; + ZFS snapshot сам по себе не доказывает согласованность репозитория. +4. Сначала закреплённые upstream/toolchain и собственные пакеты, затем sealing + общего Arch + Archipelago snapshot; после sealing содержимое неизменно. +5. HTTP registry: immutable descriptors, snapshots/packages, штатные OSTree archive + repositories, images, ISO, locks, releases; Docker-образы среды — отдельный OCI + транспорт, системные слои не превращаются в OCI images. +6. Сначала публикация всей closure и проверка через HTTP, затем атомарное обновление + подписанного channel document. OSTree discovery и портал — производные views. +7. Update, net install и портал используют один release ID и точные image/lock IDs. + Net install — загрузка выбранного image установщиком, PXE не обязателен. +8. Статический портал показывает варианты, размеры, checksums, подписи и инструкции; + у неготового варианта нет фиктивной кнопки скачивания. + +Принятые defaults: UTC, ежедневные candidate builds, ежемесячные snapshots, +одна задача на worker, overlap пропускается с записью результата, после простоя +один актуальный запуск. Точные cron-выражения и квоты — конфигурация деплоя. +Первый включённый вариант — проверенный Core x86_64. KDE/GNOME входят в обязательную +цель совместимости, но становятся доступными для скачивания после собственной приёмки. + +Принят OpenPGP trust profile с разделением ключей пакетов/OSTree/метаданных; +публичные fingerprints, хранение ключей и TLS/auth поступят с параметрами деплоя. +Лабораторный ключ текущего ISO не становится production trust root автоматически. +Testing/stable сохраняют полный D-050–D-052 gate; до него — закрытый staging. + +## 4. Минимум scriptlets/hooks — D-069 + +[RFC-0011](../rfc/RFC-0011-package-actions-compatibility.md) и +[план реализации](package-actions-plan.md): обязательный набор включает `base`, +`linux`, все интеграционные пакеты Core, KDE/GNOME Purpose и полные транзитивные +runtime/build зависимости в соответствующих контекстах. + +Инвентаризируются `.INSTALL` всех фаз, ALPM hooks, вызываемые helpers и пакеты без +действий. Каждое действие имеет источник, условия, фазу, адаптер, inputs/outputs, +порядок, timeout и проверку результата. Новые/изменённые действия не наследуют +одобрение только по имени пакета или hash верхнего скрипта. + +CLI: `hooks inventory`, `explain`, `validate`, `coverage`, `test`. Общий движок +используется layer build, composer, update и Host Extensions. Нулевой exit pacman +не отменяет провал обязательного PostTransaction действия. Неизвестные обязательные +действия не подавляются и не становятся «необязательными» ради успешной сборки. + +Gate: **ноль unclassified/stale/missing обязательных действий** и успешные действия/ +системные проверки. Для KDE/GNOME нужен действующий графический вход, session, +native provisioning и целевые службы, плюс все Core gates. + +## 5. Что согласовать + +1. Строгую модель manifest/locks/identity и per-package layout. +2. Предложенную сборку effective ALPM records с сохранением originals/provenance. +3. Полную матрицу CLI и модель plan/apply без обязательного daemon. +4. Docker Compose/cron, разделение worker/validator/publisher, HTTP/native OSTree. +5. Частоту candidate/snapshot и выбор первых публикуемых вариантов. +6. Trust/publication profile; реальные адреса и deployment bindings — позднее. +7. Обязательный Core/KDE/GNOME action floor; конкретные desktop manifests и + матрицу поддерживаемых переходов snapshots — до заявления полного покрытия. + +После согласования: `contracts`/fixtures → builder/composer/action engine → полный +CLI/update/net install → registry → Docker/cron/portal → доказательство release gates. +Хостовый Docker/nspawn isolation profile, точные package-specific adapters и +воспроизводимость требуют реальных проверок, а не только утверждения текста. diff --git a/ru/spec/decision-log.md b/ru/spec/decision-log.md index 216b013..c6bc4d6 100644 --- a/ru/spec/decision-log.md +++ b/ru/spec/decision-log.md @@ -2,6 +2,8 @@ Краткая запись архитектурных решений, обсуждённых RFC Committee. +Текущий согласованный объём собран в [реестре контрактов](contract-registry.md). + | ID | Решение | Статус | |---|---|---| | D-001 | OSTree — основа неизменяемого хранения файловой системы, коммитов, refs, deployments, обновлений и отката. | Accepted | @@ -65,6 +67,48 @@ | D-059 | По итоговому образу финализировать общие кэши схем, MIME, иконок, библиотек, vendor hwdb, выбранные локали и trust outputs дистрибутива. Изменяемые кэши шрифтов, системные аккаунты/каталоги, machine-id и SSH host keys создаются через lifecycle установленной цели. Службы запускаются в целевом deployment; начальные defaults объявляются, enablement администратора сохраняется при обновлениях. Локальные изменения trust, hwdb и конфигурации линкера требуют интеграции регенерации кэшей. Переиспользовать Arch/systemd; точные команды и пути проверять по закреплённому snapshot. Принимает эти размещения семейств действий RFC-0005 без фиксации деталей адаптеров/схем. | Accepted | | D-060 | Запрет D-029 относится к постоянным записям системных/служебных аккаунтов. Штатное выделение и освобождение systemd DynamicUser= остаётся обычным lifecycle службы, а не удалением постоянного аккаунта Archipelago. Не вводить собственный lifecycle временных идентичностей. Аккаунты с неоднозначной классификацией «пользователь/системный» остаются недоступны для удаления через Archipelago. | Accepted | | D-061 | RFC Committee утверждает RFC v0 (RFC-0001–0007) как архитектурный контракт 2026-11-04 с учётом D-020–D-060. Ратифицирует D-001–D-016 и D-018–D-019 с последующими уточнениями. Явно открытые контракты реализации, форматы, адаптеры, сборка пакетной базы, загрузочный профиль и доказательство воспроизводимости требуют согласования; иллюстративные примеры не являются стабильным API. Принятие не заявляет реализацию и не отменяет условия допуска testing/stable. Последовательно переходить к контрактам реализации и коду. | Accepted | +| D-062 | Реализовать основной бинарник archipelago и функциональные модули на Rust. Лабораторные инструменты могут использовать другие языки; схемы артефактов и интерфейсы FFI/адаптеров этим не фиксируются. | Accepted | +| D-063 | Планировать ежемесячные snapshots пакетных репозиториев, в дальнейшем создаваемые через ZFS на хосте зеркала. Отложить эту инфраструктуру до появления загружаемого рабочего экспериментального archipelago-core-latest.iso. Идентичность snapshot и воспроизводимость публичных testing/stable по-прежнему регулируются D-043/D-050; месячная метка или имя latest не заменяют неизменяемую идентичность входов. | Accepted | +| D-064 | Включить управление установкой и первым запуском в live/installed workflow archipelago: подготовку целевого диска, установку системы и отложенный provisioning с созданием основного пользователя при первой загрузке установленной ОС. По возможности использовать штатные настройщики GNOME/KDE; для Archipelago Core предоставить терминальную первую настройку CLI. Сохранить D-036: основной пользователь создаётся в первом deployment до последующих обычных целей отката. Точный профиль диска, frontend-адаптеры, состояния завершения/повтора и контракты привилегий/API открыты. | Accepted | +| D-065 | Выбран первый экспериментальный профиль Core ISO: x86_64 UEFI VM, GPT с FAT32 ESP и ext4 root, systemd-boot, без шифрования и Secure Boot. При необходимости загрузочной интеграции допускается отдельный /boot. Приёмка проверяет сборку ISO хостовым бинарником через nspawn, разметку диска и установку жизнеспособного OSTree deployment/загрузчика из live, загрузку с установленного диска, первичное создание пользователя и базовые службы, затем активацию тестового Managed Overlay и пакетного Host Extension. Схемы артефактов и адаптеры package DB экспериментальные; публичные release gates сохраняются. | Accepted | + +## Проекты контрактов реализации + +У каждой записи свой статус. D-066 явно принят 2026-11-04; +D-067–D-069 и план реализации package actions явно приняты 2026-11-04. +Реализация и явно открытые детали ещё требуются. + +| ID | Решение | Статус | +|---|---|---| +| D-066 | Приняты строгие YAML/JSON manifests намерения, SHA-256 канонического JSON независимо от транспорта, отдельные LayerLock/CompositionLock, индексированные per-package OSTree payload и effective ALPM records с сохранением originals и явным происхождением преобразований; RFC-0008. Утверждено 2026-11-04; конкретные схемы/адаптеры и доказательство реализации ещё требуются. | Accepted | +| D-067 | Принят единый CLI для build host, установленной системы и installer/live: полный каталог команд, проверяемый plan/apply под блокировкой, общие JSON/errors и журнал операций, отмена/возобновление с учётом стадии, раздельные desired/pending/booted, явные reboot/rollback/fallback, capabilities и начальная работа без обязательного daemon; RFC-0009. Утверждено 2026-11-04; реализация поэтапная. | Accepted | +| D-068 | Приняты Docker Compose с host cron и отдельными builder/KVM validator/publisher, ежемесячные immutable snapshots Arch + Archipelago и ежедневные закреплённые candidate builds, HTTP/native OSTree, публикация проверенной полноты артефактов перед атомарным подписанным указателем канала, общие release identities для update/net install/портала, OpenPGP с разделением ключей и продвижение без пересборки. Первый вариант — Core x86_64 после release gates; KDE/GNOME проходят собственную приёмку. Адреса, параметры серверов, ключи, точные расписания/лимиты и проверка изоляции workers ещё требуются; RFC-0010. Утверждено 2026-11-04. | Accepted | +| D-069 | Принято обязательное покрытие actions base/linux/Core и полных runtime dependencies KDE/GNOME, плюс build dependencies в своих контекстах; inventory scriptlets/hooks/helpers и пакетов без действий, общие versioned policy/adapters/ledger и hooks CLI. Обязательные ошибки блокируют candidate даже при exit pacman=0; готовность требует нуля unresolved mandatory actions и функциональных проверок desktop onboarding/session/services и всех Core checks. Утверждён поэтапный план от inventory до publication gates. Точные desktop manifests и поддерживаемые переходы snapshots согласуются отдельно; RFC-0011 и spec/package-actions-plan.md. Утверждено 2026-11-04. | Accepted | + +## Заморозка схемы Layer + +| ID | Решение | Статус | +|---|---|---| +| D-070 | Заморозить Layer YAML/JSON v1 после явного поблочного утверждения 2026-11-04: каркас/пакеты, runtime и наследование provisioner, lifecycle проверок, actions, files, ограниченные overrides, compatibility/replacements, точные kernel/ABI references и строгая валидация. Нормативная схема: schemas/layer-v1.schema.json; семантика: spec/layer-yaml-freeze.md и RFC-0008 в английском дереве. Изменения требуют отдельного согласования и версии схемы. Полные desktop-наборы, ABI-алгоритм, адаптеры, Composition/lock schemas и доказательство реализации остаются отдельной работой. | Accepted | + +## Инфраструктура на terra + +| ID | Решение | Статус | +|---|---|---| +| D-071 | Git-реестры YAML Core/Purpose и код инфраструктуры размещаются на git.fasoley.net в организации Archipelago рядом с rfc. Registry, ISO/home portal и CLI builders слоёв/образов/ISO размещаются на terra рядом с /opt/mirror вместо superserv1 для новых инфраструктурных работ; обязательны standalone deployment files. База URL — https://mirror.nw-sys.ru/archipelago/, ниже ISO и OSTree. Сборка из точных YAML revisions и закреплённых входов зеркала, публикация слоёв, композиция из artifact repository, затем ISO. Стиль Material You, явная независимость проекта и корректные отсылки к Arch Linux. Реализовать registry-backed CLI update, затем PackageKit/GNOME Software/KDE Discover через единый staged transaction contract. Release/trust gates D-068 сохраняются; spec/terra-infrastructure.md в английском дереве. Явно утверждено 2026-11-04. | Accepted | + +## Ежедневный экспериментальный Core и firmware + +| ID | Решение | Статус | +|---|---|---| +| D-074 | Ежедневно собирать экспериментальный Core из текущих source commits и текущего Arch mirror для сквозной проверки инфраструктуры и обновлений по image commit. Новый image commit становится update candidate; неизменившийся commit не является новым payload. Явно включать linux-firmware в Core и live installer со штатным замыканием зависимостей, не полагаясь на зависимость linux. Это не гарантия всего оборудования или наличия исходников всех прошивок. Отложенная заморозка D-073 и public gates D-050 сохраняются. Явное указание пользователя, 2026-11-05. | Accepted | + +## Snapshot-хранилище и порядок экспериментальных сборок + +| ID | Решение | Статус | +|---|---|---| +| D-072 | Для будущих captures отдельный ZFS dataset tank/archipelago, рабочее зеркало остаётся в /opt/mirror/data. Хранить не более трёх месячных snapshots. Уточнение D-063/D-068: нельзя молча удалять входы, необходимые retained releases/locks; если безопасное удаление невозможно, новый capture останавливается. Отдельное хранилище и лимит явно согласованы 2026-11-05. Включение capture затем отложено D-073. | Accepted | +| D-073 | Пока проект созревает, не создавать snapshots и не копировать зеркало целиком. Экспериментальные образы формировать из живого зеркала; приоритет — работа над воспроизводимостью и соответствием RFC. Заморозка и релизы из snapshots — позже. Сохранять точные identities/checksums входов прогона; изменение/недоступность — ошибка, не молчаливая подмена. Живое зеркало и успешный эксперимент не являются sealed Snapshot/public release. D-050 и public release gates сохраняются. Явное указание пользователя 2026-11-05. | Accepted | ## Правила статусов diff --git a/ru/spec/layer-yaml-freeze.md b/ru/spec/layer-yaml-freeze.md new file mode 100644 index 0000000..cfcdf13 --- /dev/null +++ b/ru/spec/layer-yaml-freeze.md @@ -0,0 +1,26 @@ +# Замороженный формат Layer YAML/JSON v1 + +**Статус: Accepted, D-070, 2026-11-04.** Пользователь утвердил все блоки и явно +согласовал заморозку. Нормативные определения: + +- [JSON Schema](../../schemas/layer-v1.schema.json), + [правила проверки](../../schemas/README.md). +- [Полный протокол согласованных блоков](../../spec/layer-yaml-freeze.md). +- [RFC-0008](../../rfc/RFC-0008-manifests-locks-and-artifacts.md). + +Заморожены каркас Layer и пакетные требования; runtime, наследование provisioner, +службы и lifecycle проверок; actions; files; ограниченные overrides; compatibility +и замены пакетов; точные kernel/ABI references; строгий YAML и уровни валидации. + +Примеры: [Core](../../examples/v1/core.layer.yaml), +[GNOME](../../examples/v1/gnome.layer.yaml), [KDE](../../examples/v1/kde.layer.yaml). +Списки пакетов иллюстративны; полные desktop-наборы и адаптеры ещё согласуются. +Примеры не объявляют действующий CLI-парсер или готовый desktop-образ. + +Проверки выполняются последовательно: строгий разбор → структурная схема → +семантика исходников → resolve/build → полная композиция. Схема сама по себе +не проверяет package DB, ABI, классификацию hooks, файловую систему и загрузку. + +Изменение полей или семантики требует отдельного согласования и версии схемы. +Composition/lock/artifact schemas, конкретный ABI-алгоритм и доказательства +реализации не заморожены этим решением. diff --git a/ru/spec/open-questions.md b/ru/spec/open-questions.md index aa72205..a6217c3 100644 --- a/ru/spec/open-questions.md +++ b/ru/spec/open-questions.md @@ -6,8 +6,41 @@ RFC v0 принят как архитектурный контракт по D-061. [Ревизия утверждения](rfc-v0-approval-review.md) фиксирует результаты обсуждения политик и оставшиеся условия реализации. Явно открытые варианты ещё требуют согласования до стабилизации соответствующей реализации; номера вопросов сохранены. +## Проекты контрактов на рассмотрении + +D-071 задаёт параметры развёртывания для вопросов 15, 16 и 22: Git в +git.fasoley.net/Archipelago, terra рядом с `/opt/mirror`, HTTP/native OSTree и +ISO/home portal под `/archipelago/`, обязательны standalone-файлы. См. +[направление развёртывания](terra-infrastructure.md). Lock/release wire schemas, +хранение ключей/fingerprints, квоты/расписания, snapshot capture и изоляция workers +ещё открыты; это не подтверждение готовности pipeline или update client. + +RFC-0008/D-066 принят 2026-11-04: семантика manifests/locks/identity, +per-package payload и effective ALPM. Конкретные схемы и адаптеры ещё открыты. +Каталог CLI и lifecycle RFC-0009/D-067 приняты 2026-11-04; реализация и проверки +ещё требуются. Инфраструктура и публикация RFC-0010/D-068 приняты 2026-11-04; +параметры развёртывания и проверка изоляции workers ещё открыты. +RFC-0011/D-069 и поэтапный план приняты 2026-11-04; точные desktop manifests, +переходы snapshots и доказательства адаптеров ещё требуются. Детали реализации в вопросах ниже +сохраняются; [обзор согласования](contracts-v1-review.md) отражает решения. + +- RFC-0008: manifests/locks/indexes/identity и ALPM accounting — вопросы 1–8, + 19, 46–47, 50–55, 61–62; схемы и adapter proof следуют после утверждения семантики. +- RFC-0009: CLI, plan/apply, состояния/capabilities — 29–36, 41–45, 57, 65, 68–69, 72. +- RFC-0010: Docker/cron, snapshots, HTTP/OSTree, trust/publication, net install/portal — + 15–22, 26, 66, 70–71; адреса, worker isolation profile и cron-конфигурация позже. +- RFC-0011: обязательный минимум scripts/hooks base/linux/Core плюс полные + согласованные KDE/GNOME наборы — 52–56, 70–72. Конкретные desktop manifests и + transition matrix требуют review; [план](package-actions-plan.md) разделяет + inventory, policy, adapters, execution evidence и publication gates. + ## Модель слоёв и композиции +D-070 замораживает авторскую схему Layer и локальные правила из вопросов +2, 4, 5, 41, 49 и 55: [схема](../../schemas/README.md), +[протокол](../../spec/layer-yaml-freeze.md). Детали Composition/locks/artifacts, +runtime evidence и адаптеры остаются открытыми в соответствующих вопросах. + 1. D-044 выбирает отдельные пространства payload и metadata внутри коммита слоя. Какие точные имена, схема и сериализация определяют стабильный формат артефакта? `payload/` и `metadata/` — иллюстративные имена. 2. D-055 требует ровно один Core и ноль или один Purpose; Archipelago Core поставляется без Purpose. Как необязательный выбор Purpose и совместимость выражаются в схеме и интерфейсе управления? 3. Какая семантика решателя зависимостей нужна: диапазоны версий, ограничения функций, архитектуры и декларации конфликтов? @@ -34,6 +67,8 @@ RFC v0 принят как архитектурный контракт по D-06 16. Какой транспорт OSTree и серверная реализация реестра выбираются? 17. Как управляются аутентификация реестров, ключи подписей, корни доверия и ротация ключей? 18. Какие пакетные репозитории и snapshots Arch Linux Archive поддерживаются? + D-063 планирует ежемесячные snapshots через ZFS на хосте зеркала после рабочего + экспериментального Core ISO. Точные протоколы захвата, хранения и публикации открыты. 19. D-042 отделяет намерение манифеста от разрешённых закреплённых входов, с явным resolve/update и без скрытой подмены при build/compose. Какая точная схема lockfile фиксирует слои, snapshot, идентичности пакетов, архитектуру и входы финализации, и как проверяются идентичности и совместимость manifest/lock? 20. Какой контракт ключа и инвалидации сборочного кэша необходим? 21. Как представляются OCI-среды сборки, если будут приняты? @@ -41,8 +76,14 @@ RFC v0 принят как архитектурный контракт по D-06 ## Система и установщик +D-064 выбирает отложенное создание основного пользователя при первом boot, +терминальную настройку Core и штатные мастера GNOME/KDE, где возможно. Вопрос 57 +сохраняет границы D-036; вопрос 72 отслеживает оставшийся контракт control layer. + 23. D-033 первоначально выбирает systemd-boot. Какой точный профиль UEFI/BLS, ESP/XBOOTLDR и пакетной интеграции mkinitcpio требуется? 24. Каковы стандартные файловая система и разметка MVP: ext4 или Btrfs, единый root или отдельные разделы состояния? + D-065 выбирает GPT/FAT32 ESP/ext4 root для первого экспериментального ISO x86_64 + UEFI VM; при необходимости допускается отдельный /boot. Production-детали открыты. 25. Как показываются трёхстороннее слияние `/etc` OSTree и конфликты конфигурации? 26. Как устроены офлайн-наборы установки? 27. В каком порядке LUKS2, TPM2 и Secure Boot входят в roadmap? @@ -80,6 +121,10 @@ RFC v0 принят как архитектурный контракт по D-06 D-024 решает принцип владения: один фактический владелец пакета, переиспользование нижних пакетов, отсутствующие зависимости принадлежат расширяющему слою, замены overlays явны, требования отделены от payload. D-025 определяет общие зависимости: первый требующий слой в детерминированном порядке владеет отсутствующей ниже зависимостью; остальные переиспользуют её. Удаление владельца вызывает переназначение в новой композиции, если пакет ещё нужен. Входные коммиты неизменны. Включение пакетов на уровне артефактов и построение итоговой базы pacman открыты. 47. D-023 требует общий snapshot; D-043 определяет неизменяемый упорядоченный набор репозиториев Arch и Archipelago, целевую архитектуру, контрольные суммы баз и идентичности пакетов с вычисленным из содержимого snapshot_id. Точная схема описания, канонизация, проверка и метаданные доверия открыты. 48. Какие пакеты дополняют `base` и `linux` в Core для firmware, initramfs и загрузочной/deployment-интеграции OSTree (D-021)? + D-074 определяет baseline firmware: явный `linux-firmware` со штатными + зависимостями в Core/live installer. Остальные integration inputs и hardware + evidence открыты. D-072/D-073 откладывают snapshots (будущий лимит — три), + D-074 задаёт ежедневный экспериментальный Core из текущих исходников/live mirror. 49. D-041 различает роль и конкретный вариант; D-055 меняет количество на ноль или один Purpose, включая поздний выбор из Archipelago Core. Несколько DE могут выражаться специальным вариантом или Managed Overlay. Выбор DM, переключение systemd и другая desktop-интеграция относятся к контракту Purpose. Какая точная схема выражает роль, вариант и совместимость overlays? Конкретное содержимое/lifecycle Purpose и рецензирование пользовательских наборов для официального принятия остаются отдельными задачами. 50. При замене пакетов или общих библиотек верхними слоями как повторно проверяются зависимости всей итоговой композиции и отклоняются несовместимые замены? D-038 требует явного намерения замены целого пакета и проверки зависимостей, конфликтов, владения и применимого ABI ядра всей композиции. Точная схема и реализация проверки открыты; файловые overrides Managed Overlay остаются отдельной операцией с provenance. @@ -119,3 +164,8 @@ RFC v0 принят как архитектурный контракт по D-06 70. Как доказывается полная воспроизводимость D-050 для testing/stable: канонические метаданные коммита, детерминированные генераторы/toolchain-входы, сравнение образов и релизных артефактов, обработка подписей/аттестаций и независимые пересборки? Как фиксируются изменения локального дерева исходников для воспроизводимости экспериментов? 71. D-051 задаёт минимальные функциональные условия публичных каналов: загрузка/локальный вход Core, установка Host Extension, применение Managed Overlay и работа заявленных служб Purpose в чистой среде. Какие тестовые пакеты/overlays, поддерживаемые VM/аппаратные профили, пробы служб и автоматизированный harness это реализуют? Функциональные тесты не заменяют доказательство воспроизводимости из вопроса 70. D-052 требует выполнения всех проверок Core на каждом полном релизном кандидате Core + Purpose в дополнение к проверкам его служб. +72. Как live installer передаёт управление first-boot provisioning (D-064): идентичность + target и прерывание дисковых операций, определение контекста, выбор frontend, + владение локальной консолью, привилегии, доказательство завершения, повторы и + сериализация с подготовкой deployment? Как интегрировать сеансы GNOME/KDE без + повторного создания аккаунта при добавлении Purpose к настроенному Core? diff --git a/ru/spec/package-actions-plan.md b/ru/spec/package-actions-plan.md new file mode 100644 index 0000000..23e41cd --- /dev/null +++ b/ru/spec/package-actions-plan.md @@ -0,0 +1,90 @@ +# План реализации package actions в archipelago CLI + +**Статус: Accepted — D-069, 2026-11-04.** Поэтапный план RFC-0011 утверждён. +Это не подтверждение готовности текущих адаптеров или допуска к публичному релизу. +Конкретные desktop manifests и поддерживаемые переходы snapshots ещё согласуются. + +## Текущее состояние + +Core ISO прошёл VM-проверки и, по сообщению пользователя, ручную проверку. +Repository-backed extensions тестируются. Сейчас есть Core hook hash inventory, +проверка входящих actions и частично анализ текста transaction log. Полного +version-aware покрытия, native desktop setup и KDE/GNOME session evidence ещё нет. + +## Ответственность модулей + +- `contracts`: Rust-типы/схемы ActionInventory, PackageActionPolicy, CoverageReport, + ActionResult, канонические IDs и validation. +- `builder`: verified inventory, libalpm transactions, build actions и ledger. +- `composer`: finalizer DAG, generated ownership и coverage gate. +- `system`: runtime units, общая политика для extensions/update, результаты boot/deployment. +- `installer`: deployment/boot actions, native/terminal provisioning adapters. +- `cli`: hooks-команды, JSON/errors, progress/diagnostics. +- `manifests`: точные Core/KDE/GNOME наборы, runtime contracts, policy references. +- `registry`: хранение policies/attestations с immutable IDs. +- `test-lab`: isolated fixtures, transitions/failures и desktop VM checks. + +Основная реализация — Rust. Shell допустим как явно закреплённый snapshot adapter, +но не как второй самостоятельный policy engine. Используются штатные libalpm/systemd. + +## P0. Зафиксировать наборы + +Согласовать Core/KDE/GNOME manifests: DM, onboarding, session и необходимые +интеграции. Разрешить полные runtime/build зависимости, providers, версии/checksums +на одном snapshot. Выход: утверждённые manifests/locks/functional profiles. +Gate: нет плавающих групп или исключения обязательного пакета ради обхода action. + +## P1. Инвентаризация без исполнения + +Реализовать `hooks inventory` по архивам и transaction root: `.INSTALL`, hooks, +precedence/overrides, helpers/conditions, no-action entries. Сложное динамическое +поведение требует review. Тесты: отсутствующие архивы, опасные пути, shadowed hooks, +смена helper, новый hook на старых файлах. Gate: учтён каждый выбранный пакет. + +## P2. Policy и coverage + +Схемы/валидация Rust; `hooks explain`, `validate`, `coverage`. Проверки фаз, +DAG/outputs, timeout/network, required и inapplicable predicates. Негативные fixtures: +unknown/stale input, wrong snapshot, исторические migrations, mixed-phase function, +suppressed hook без замены. Gate: unresolved mandatory action не даёт успех. + +## P3. Ledger и Core + +Интеграция с native libalpm order/NeedsTargets, действительными status/outputs. +Exit pacman=0 не отменяет failed ledger entry. Проверить kernel/depmod/mkinitcpio, +linker/locale/trust, hwdb/catalog, sysusers/tmpfiles, service lifecycle, keyring, +machine identity. Mixed-phase scripts адаптируются явно. Финализация полного дерева +offline; generated ownership фиксируется. Gate: fresh/transition/failure tests Core, +отсутствие влияния на live services/package DB/ESP/persistent state. + +## P4. GNOME и KDE + +Инспекция дополнительных closures и shared adapters для schemas/GIO/GdkPixbuf, +MIME/desktop/icons/fonts, trust, accounts/permissions и defaults. DM/session/onboarding +остаются политикой Purpose. Для обязательных пакетов заранее закрыть persistence, +UID и placement adapters. VM: clean install, native setup либо согласованный adapter, +реальный графический login/session, службы, reboot без повторной настройки, +сохранение administrator choices и все Core overlay/extension gates. +Gate: Core+GNOME и Core+KDE проходят независимо. + +## P5. Переходы и локальные композиции + +Сравнивать snapshot inventories; изменения source/helper/trigger инвалидируют +затронутые результаты. Проверить upgrade branches, полный набор extensions, +recomposition/removal, staged replacement, rollback, runtime retries и сохранение +IDs/данных. Gate: required failure сохраняет booted/pending/rollback и local inputs; +нет частичного fallback, stale global success marker или live mutation. + +## P6. Инфраструктурный gate + +Docker/cron вызывает тот же CLI. Publisher проверяет coverage/tests для точных +lock/policy IDs. Новый unknown action оставляет failed private run и прежний public +release pointer. История policies/evidence сохраняется; диагностика указывает +source/adapter owner. Проверить восстановление точной policy по историческому lock. + +## Завершение + +Во всех трёх согласованных минимальных профилях нет unresolved mandatory actions, +пройдены action/full-system tests и поддерживаемые snapshot transitions. +Воспроизводимость и остальные public gates — отдельно. Поддержка внешних optional +пакетов не заменяет завершения обязательного Core/KDE/GNOME набора. diff --git a/ru/spec/terra-infrastructure.md b/ru/spec/terra-infrastructure.md new file mode 100644 index 0000000..589ec62 --- /dev/null +++ b/ru/spec/terra-infrastructure.md @@ -0,0 +1,72 @@ +# Развёртывание на terra и desktop updates + +[English — полный контракт](../../spec/terra-infrastructure.md) + +**Accepted: D-071, 2026-11-04.** Согласованы направление и параметры развёртывания; +конкретные release wire schemas и GUI adapters ещё требуют реализации и проверки. + +## Исходники и размещение + +Git-организация `https://git.fasoley.net/Archipelago/`: `core` — YAML Core, +`purposes` — YAML Purpose, `infrastructure` — Docker/cron/registry/portal/deploy, +рядом с `rfc`. Сборки закрепляют Git commit и digest исходников. Desktop proposals +отключены до согласования полных наборов. Исходники инфраструктуры хранятся и на terra. + +Новые сборки, валидация и публикация выполняются на terra вместо superserv1. +Завершение ранее начатых лабораторных проверок допускается с сохранением evidence. +Интеграция рядом с `/opt/mirror`; standalone deployment обязателен. + +База `https://mirror.nw-sys.ru/archipelago/`: + +- `/` — homepage и ISO portal; +- `iso/` — допущенные неизменяемые ISO/checksums/signatures; +- `ostree/layers/` — native archive repository слоёв; +- `ostree/images/` — native archive repository полных образов; +- `v1/` — metadata/release/channel namespaces RFC-0010. + +Private staging отделён от публичного корня и закрыт доступом; отсутствие ссылки +на портале не является изоляцией. Публичность homepage не разрешает публикацию +экспериментальных ISO. Маршруты Arch mirror сохраняются. + +## Pipeline и оформление + +CLI разрешает YAML и закреплённые входы зеркала, строит независимые слои, размещает +их в artifact repository, компонует точные commits, затем строит и публикует ISO. +Композиция не переустанавливает managed packages для получения их payload. +Сохраняются отдельные builder/KVM validator/publisher, offline finalization, +полная воспроизводимость, обязательные gates и подписанное атомарное продвижение. +Монолитный экспериментальный ISO builder не является готовым pipeline. + +D-072 выбирает отдельный `tank/archipelago` для будущих captures и лимит **трёх +месячных snapshots**. Рабочее зеркало `/opt/mirror/data` находится на Btrfs; +`tank/mirror` — отдельная копия. Если все три снимка ещё нужны retained releases/ +locks, создание четвёртого останавливается. Лимит количества не заменяет byte quota. +D-073 откладывает snapshots и полное копирование зеркала: экспериментальные сборки +используют живое зеркало с фиксацией/checksums входов и отказом при их изменении. +Заморозка для релиза позже, public gates сохраняются. Capture и snapshot cron отключены. + +D-074 задаёт ежедневный экспериментальный Core из актуальных source commits и +живого зеркала для сквозной проверки сборки/доставки/обновлений по image commit. +`linux-firmware` включается явно в Core и live installer со штатными зависимостями. +Это не гарантия всего оборудования или открытых исходников всех firmware blobs. +Ежедневный candidate не получает допуск testing/stable автоматически. + +Homepage — Material You-inspired, с оригинальной графикой, описанием, исходниками +и проверенными ISO. Явно указывать независимость от Arch Linux, upstream-ссылку +и принадлежность товарных знаков; не подразумевать одобрение upstream. + +## Обновления + +Сначала CLI check/plan/apply: аутентифицированное обнаружение, проверка точных +image/lock, preconditions под блокировкой, атомарное применение полного набора +Host Extensions, валидация и OSTree staging. Ошибка сохраняет booted/pending; +перезагрузка явная. Самописная композиция и overlays не отбрасываются молча. + +Затем PackageKit и GNOME Software/KDE Discover, использующие те же планы, +блокировки, прогресс, ошибки, отмену, привилегии и reboot-required. Это OS-image +transaction; live `pacman -Syu` и независимый выбор пакетных обновлений не подходят. +KDE Store — магазин контента, UI обновлений называется Discover. Необходимость +frontend plugins проверяется по выбранным версиям; работающий GUI не подразумевается. + +Открыты точные wire schemas, ключи/хранение, storage quotas, воспроизводимость, +API/Polkit mapping и проверки staging/reboot/failure на обоих desktop Purposes. diff --git a/schemas/README.md b/schemas/README.md new file mode 100644 index 0000000..c1961a7 --- /dev/null +++ b/schemas/README.md @@ -0,0 +1,56 @@ +# Frozen Layer v1 + +`layer-v1.schema.json` is the normative structural JSON Schema (2020-12) for +`apiVersion: archipelago/v1`, `kind: Layer`, frozen by explicit user approval on +2026-11-04. YAML and JSON use the same data model. Composition/lock schemas are +separate and are not frozen by this Layer schema. + +Normative semantics: [RFC-0008](../rfc/RFC-0008-manifests-locks-and-artifacts.md) +and [agreed freeze blocks](../spec/layer-yaml-freeze.md). Complete YAML examples: +[Core](../examples/v1/core.layer.yaml), [GNOME](../examples/v1/gnome.layer.yaml), +[KDE](../examples/v1/kde.layer.yaml). Package lists and adapter names in examples +are illustrative, not approved complete desktop profiles or working adapters. + +## Validation pipeline + +1. Strict UTF-8 parsing: one document, no duplicate keys, anchors, aliases, merge + keys, custom tags, implicit type coercion, null substitution or interpolation. + Preserve plain text as text except JSON-compatible booleans/numbers/null, then + validate the actual types. Floats are forbidden; integers use the JSON-safe range. +2. Validate the parsed object against the schema. `default` annotations describe + canonicalization; JSON Schema validators do not insert them automatically. + Apply defaults only to applicable fields (never inject forbidden fields such + as Core replacements). Missing file type is `file`, missing required flag true. +3. Semantic validation checks keyed uniqueness (packages within each requirement + list, actions, units, canonical paths), references, DAGs, adapter contracts, + source-tree containment, preset conflicts and override relationships. Build + requirements can legitimately name the same package as runtime requirements. +4. Resolve/build validates exact package inputs, identities, declared system + ownership, source paths and complete package-action coverage. +5. Composition validates ownership, effective package records, compatibility, + ordered overlays, replacements/overrides, kernel/ABI and finalization. Verify + expected_sha256 keys against paths and require regular-file targets. + +Structural success never establishes image readiness. The fixture runner below +checks parser/structural and selected source-local semantic requirements; it is not +the production Rust parser, package resolver or composition engine. + +## Fixtures + +Run new checks on terra (D-071) with Python `jsonschema` and `PyYAML` in an isolated environment: + +```sh +python rfc/schemas/check-fixtures.py +``` + +The runner validates committed examples and negative mutations: unknown fields, +type errors, unsafe paths, conditional fields, kernel binding, duplicate identities, +missing action references, action cycles and parser-level duplicate/alias/multidoc +rejection. Add conformance fixtures when implementing the Rust `contracts` parser. +Schema or semantic changes require separate approval and schema versioning. + +The workspace Rust `contracts` module now implements parsing, structural validation, +keyed uniqueness, check references and action DAG checks. Its CLI command is +`archipelago layer validate FILE`. Full source/adapter/resolution/composition checks +remain pending. `infrastructure/tests/layer-conformance.py` compares its results with +these reference fixtures; this is implementation evidence, not a schema change. diff --git a/schemas/check-fixtures.py b/schemas/check-fixtures.py new file mode 100644 index 0000000..f0a77ab --- /dev/null +++ b/schemas/check-fixtures.py @@ -0,0 +1,149 @@ +"""Layer v1 conformance fixtures; run on the lab host, not a production parser.""" +import copy +import json +from pathlib import Path +import re + +import jsonschema +import yaml + +ROOT = Path(__file__).resolve().parents[1] +SCHEMA = json.loads((ROOT / "schemas/layer-v1.schema.json").read_text()) +jsonschema.Draft202012Validator.check_schema(SCHEMA) +VALIDATOR = jsonschema.Draft202012Validator(SCHEMA) + + +def parse(text): + # BaseLoader preserves scalar spellings; resolve only JSON-compatible scalars. + for token in yaml.scan(text): + if isinstance(token, (yaml.tokens.AnchorToken, yaml.tokens.AliasToken, yaml.tokens.TagToken)): + raise ValueError("anchors/aliases/tags are forbidden") + documents = list(yaml.compose_all(text, Loader=yaml.BaseLoader)) + if len(documents) != 1 or documents[0] is None: + raise ValueError("exactly one document is required") + + def convert(node): + if isinstance(node, yaml.MappingNode): + result = {} + for key, value in node.value: + key = convert(key) + if not isinstance(key, str) or key == "<<" or key in result: + raise ValueError("invalid/duplicate mapping key") + result[key] = convert(value) + return result + if isinstance(node, yaml.SequenceNode): + return [convert(item) for item in node.value] + value = node.value + if node.style is None: + if value in ("true", "false", "null"): + return json.loads(value) + if re.fullmatch(r"-?(0|[1-9][0-9]*)", value): + number = int(value) + if abs(number) > 9007199254740991: + raise ValueError("integer outside interoperable range") + return number + if re.fullmatch(r"-?(0|[1-9][0-9]*)(\.[0-9]+([eE][+-]?[0-9]+)?|[eE][+-]?[0-9]+)", value): + raise ValueError("floats are forbidden") + return value + + return convert(documents[0]) + + +def validate(data): + VALIDATOR.validate(data) + spec = data["spec"] + for entries, key in [ + (spec.get("packages", {}).get("runtime", []), "name"), + (spec.get("packages", {}).get("build", []), "name"), + (spec.get("actions", []), "id"), + (spec.get("runtime", {}).get("units", []), "name"), + (spec.get("files", []), "path"), + ]: + values = [item[key] for item in entries] + if len(set(values)) != len(values): + raise ValueError(f"duplicate {key}") + actions = {item["id"]: item for item in spec.get("actions", [])} + for field in ("boot_checks", "functional_checks"): + if any(ref not in actions for ref in spec.get("runtime", {}).get(field, [])): + raise ValueError("missing check reference") + visited, active = set(), set() + + def visit(name): + if name not in actions or name in active: + raise ValueError("missing predecessor or action cycle") + if name in visited: + return + active.add(name) + for predecessor in actions[name].get("after", []): + visit(predecessor) + active.remove(name) + visited.add(name) + + for name in actions: + visit(name) + return data + + +base = parse((ROOT / "examples/v1/core.layer.yaml").read_text()) +count = 0 +for path in sorted((ROOT / "examples/v1").glob("*.layer.*")): + validate(parse(path.read_text())) + count += 1 + +# Exercise successful conditional branches, not just their rejection paths. +full = copy.deepcopy(base) +full["spec"].update(type="purpose", purpose={"role": "desktop", "variant": "test"}) +full["spec"]["compatibility"] = {"core": ["core/arch"], "kernel": { + "package": {"name": "linux", "version": "1:1.0-1", "architecture": "x86_64", "archive_sha256": "sha256:" + "a" * 64}, + "release": "1.0-arch1", "abi": {"adapter": "linux-module-abi/v1", "digest": "sha256:" + "b" * 64}}} +full["spec"]["files"] = [ + {"path": "/usr/share/example", "source": "files/example", "mode": "0644", "owner": "root", "group": "root"}, + {"type": "directory", "path": "/usr/share/example-dir", "mode": "0755", "owner": "root", "group": "root"}, + {"type": "symlink", "path": "/usr/share/example-link", "target": "example", "mode": "0777", "owner": "root", "group": "root"}, +] +full["spec"]["overrides"] = [{"operation": "replace-file", "paths": ["/usr/share/example"], + "expected_owner": {"layer": "core/arch", "package": "example"}, "reason": "fixture", + "expected_sha256": {"/usr/share/example": "sha256:" + "c" * 64}}] +validate(full) +count += 1 + + +def reject(label, mutate): + global count + data = copy.deepcopy(base) + mutate(data) + try: + validate(data) + except (ValueError, jsonschema.ValidationError): + count += 1 + return + raise AssertionError(f"accepted invalid fixture: {label}") + + +reject("unknown field", lambda x: x["spec"].update(unknown=True)) +reject("newline identity", lambda x: x["metadata"].update(name="core/arch\n")) +reject("null runtime", lambda x: x["spec"].update(runtime=None)) +reject("core purpose", lambda x: x["spec"].update(purpose={"role": "desktop", "variant": "gnome"})) +reject("missing purpose", lambda x: x["spec"].update(type="purpose")) +reject("core replacements", lambda x: x["spec"]["packages"].update(replacements=[])) +reject("core ordering", lambda x: x["spec"].update(compatibility={"after": []})) +reject("duplicate package", lambda x: x["spec"]["packages"]["runtime"].append({"name": "base", "constraint": ">=1"})) +reject("duplicate action", lambda x: x["spec"]["actions"].append(copy.deepcopy(x["spec"]["actions"][0]))) +reject("unknown check", lambda x: x["spec"]["runtime"].update(boot_checks=["missing"])) +reject("cycle", lambda x: x["spec"]["actions"][0].update(after=["core-ostree-boot"])) +reject("timeout zero", lambda x: x["spec"]["actions"][0].update(timeout_seconds=0)) +reject("finalize network", lambda x: x["spec"]["actions"][0].update(phase="finalize", network="allowed")) +reject("partial kernel", lambda x: x["spec"].update(compatibility={"kernel": {"release": "test"}})) +for path in ("/../etc/x", "/usr/../etc/x", "/usr//x", "relative"): + reject("unsafe path", lambda x, p=path: x["spec"].update(files=[{"type": "directory", "path": p, "mode": "0755", "owner": "root", "group": "root"}])) +reject("recursive directory", lambda x: x["spec"].update(files=[{"type": "directory", "source": "files", "path": "/usr/x", "mode": "0755", "owner": "root", "group": "root"}])) +reject("numeric mode", lambda x: x["spec"].update(files=[{"type": "directory", "path": "/usr/x", "mode": 755, "owner": "root", "group": "root"}])) +reject("metadata xattr", lambda x: x["spec"].update(overrides=[{"operation": "set-metadata", "paths": ["/usr/x"], "expected_owner": {"layer": "core/arch"}, "reason": "test", "metadata": {"xattrs": {}}}])) +for text in ("a: 1\na: 2", "a: &a x\nb: *a", "a: !!str x", "a: x\n---\nb: y", "a: 1.5", "a: 9007199254740992", "<<: {}"): + try: + parse(text) + except ValueError: + count += 1 + else: + raise AssertionError(f"accepted invalid YAML: {text}") +print(f"PASS: {count} Layer v1 examples and rejection fixtures") diff --git a/schemas/layer-v1.schema.json b/schemas/layer-v1.schema.json new file mode 100644 index 0000000..a28f100 --- /dev/null +++ b/schemas/layer-v1.schema.json @@ -0,0 +1,151 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archipelago:schema:layer:v1", + "title": "Archipelago Layer v1", + "type": "object", + "additionalProperties": false, + "required": ["apiVersion", "kind", "metadata", "spec"], + "properties": { + "apiVersion": {"const": "archipelago/v1"}, + "kind": {"const": "Layer"}, + "metadata": { + "type": "object", "additionalProperties": false, + "required": ["name", "version"], + "properties": { + "name": {"$ref": "#/$defs/id"}, + "version": {"type": "string", "pattern": "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(\\.(0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*))?(\\+[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?(?![\\s\\S])"} + } + }, + "spec": { + "type": "object", "additionalProperties": false, + "required": ["type", "architecture"], + "properties": { + "type": {"enum": ["core", "purpose", "overlay"]}, + "architecture": {"const": "x86_64"}, + "purpose": { + "type": "object", "additionalProperties": false, + "required": ["role", "variant"], + "properties": {"role": {"enum": ["desktop", "server", "iot"]}, "variant": {"$ref": "#/$defs/localId"}} + }, + "packages": { + "type": "object", "additionalProperties": false, "default": {}, + "properties": { + "runtime": {"$ref": "#/$defs/requirements"}, + "build": {"$ref": "#/$defs/requirements"}, + "replacements": { + "type": "array", "default": [], "uniqueItems": true, + "items": { + "type": "object", "additionalProperties": false, + "required": ["target", "replacement", "expected_owner", "reason"], + "properties": {"target": {"$ref": "#/$defs/packageName"}, "replacement": {"$ref": "#/$defs/packageName"}, "expected_owner": {"$ref": "#/$defs/id"}, "reason": {"$ref": "#/$defs/nonempty"}} + } + } + } + }, + "compatibility": { + "type": "object", "additionalProperties": false, "default": {}, + "properties": { + "core": {"$ref": "#/$defs/ids"}, "purpose": {"$ref": "#/$defs/ids"}, + "requires": {"$ref": "#/$defs/ids"}, "conflicts": {"$ref": "#/$defs/ids"}, + "before": {"$ref": "#/$defs/ids"}, "after": {"$ref": "#/$defs/ids"}, + "kernel": { + "type": "object", "additionalProperties": false, "required": ["package", "release", "abi"], + "properties": { + "package": { + "type": "object", "additionalProperties": false, "required": ["name", "version", "architecture", "archive_sha256"], + "properties": {"name": {"$ref": "#/$defs/packageName"}, "version": {"$ref": "#/$defs/nonempty"}, "architecture": {"const": "x86_64"}, "archive_sha256": {"$ref": "#/$defs/digest"}} + }, + "release": {"type": "string", "pattern": "^[A-Za-z0-9_+.-]+(?![\\s\\S])"}, + "abi": {"type": "object", "additionalProperties": false, "required": ["adapter", "digest"], "properties": {"adapter": {"$ref": "#/$defs/adapter"}, "digest": {"$ref": "#/$defs/digest"}}} + } + } + } + }, + "files": {"type": "array", "default": [], "items": {"$ref": "#/$defs/file"}}, + "overrides": {"type": "array", "default": [], "items": {"$ref": "#/$defs/override"}}, + "actions": {"type": "array", "default": [], "items": {"$ref": "#/$defs/action"}}, + "runtime": { + "type": "object", "additionalProperties": false, "default": {}, + "properties": { + "sysusers": {"$ref": "#/$defs/vendorPaths"}, "tmpfiles": {"$ref": "#/$defs/vendorPaths"}, "presets": {"$ref": "#/$defs/vendorPaths"}, + "units": { + "type": "array", "default": [], "items": { + "type": "object", "additionalProperties": false, "required": ["name", "activation"], + "properties": {"name": {"type": "string", "pattern": "^[^/\\s]+\\.(service|socket|target|timer|path|mount|automount|swap)(?![\\s\\S])"}, "activation": {"enum": ["enable", "socket", "manual"]}}, + "if": {"properties": {"activation": {"const": "socket"}}}, + "then": {"properties": {"name": {"pattern": "\\.socket$"}}} + } + }, + "provisioner": {"$ref": "#/$defs/adapter"}, + "boot_checks": {"$ref": "#/$defs/localIds"}, "functional_checks": {"$ref": "#/$defs/localIds"} + } + } + }, + "allOf": [ + {"if": {"properties": {"type": {"const": "purpose"}}}, "then": {"required": ["purpose"]}, "else": {"not": {"required": ["purpose"]}}}, + {"if": {"properties": {"type": {"const": "core"}}}, "then": {"properties": { + "packages": {"not": {"required": ["replacements"]}}, + "compatibility": {"not": {"anyOf": [{"required": ["core"]}, {"required": ["purpose"]}, {"required": ["requires"]}, {"required": ["conflicts"]}, {"required": ["before"]}, {"required": ["after"]}]}} + }}}, + {"if": {"properties": {"type": {"const": "purpose"}}}, "then": {"properties": {"compatibility": {"not": {"anyOf": [{"required": ["purpose"]}, {"required": ["before"]}, {"required": ["after"]}]}}}}} + ] + } + }, + "$defs": { + "nonempty": {"type": "string", "minLength": 1, "pattern": "\\S"}, + "id": {"type": "string", "maxLength": 128, "pattern": "^[a-z0-9][a-z0-9._-]*(/[a-z0-9][a-z0-9._-]*)*(?![\\s\\S])"}, + "localId": {"type": "string", "maxLength": 128, "pattern": "^[a-z0-9][a-z0-9._-]*(?![\\s\\S])"}, + "adapter": {"$ref": "#/$defs/id"}, + "digest": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}(?![\\s\\S])"}, + "packageName": {"type": "string", "pattern": "^[A-Za-z0-9_+@][A-Za-z0-9_+@.-]*(?![\\s\\S])"}, + "identity": {"type": "string", "pattern": "^[a-z_][a-z0-9_-]*[$]?(?![\\s\\S])"}, + "path": {"type": "string", "pattern": "^(?!.*(?:^|/)\\.\\.?(?:/|$))/(?:[^/\\r\\n]+/)*[^/\\r\\n]+(?![\\s\\S])"}, + "ids": {"type": "array", "default": [], "uniqueItems": true, "items": {"$ref": "#/$defs/id"}}, + "localIds": {"type": "array", "default": [], "uniqueItems": true, "items": {"$ref": "#/$defs/localId"}}, + "strings": {"type": "array", "default": [], "items": {"type": "string"}}, + "vendorPaths": {"type": "array", "default": [], "uniqueItems": true, "items": {"allOf": [{"$ref": "#/$defs/path"}, {"pattern": "^/usr/"}]}}, + "requirements": {"type": "array", "default": [], "uniqueItems": true, "items": { + "type": "object", "additionalProperties": false, "required": ["name"], + "properties": {"name": {"$ref": "#/$defs/packageName"}, "constraint": {"type": "string", "pattern": "^(>=|<=|=|>|<)[^<>=\\s]+(?![\\s\\S])"}} + }}, + "file": { + "type": "object", "additionalProperties": false, "required": ["path", "mode", "owner", "group"], + "properties": { + "type": {"enum": ["file", "directory", "symlink"], "default": "file"}, + "source": {"type": "string", "pattern": "^(?!/)(?!.*(?:^|/)\\.\\.?(?:/|$))(?!.*//)[^\\r\\n]+(?![\\s\\S])"}, + "target": {"$ref": "#/$defs/nonempty"}, "path": {"$ref": "#/$defs/path"}, + "mode": {"type": "string", "pattern": "^0?[0-7]{4}(?![\\s\\S])"}, + "owner": {"$ref": "#/$defs/identity"}, "group": {"$ref": "#/$defs/identity"} + }, + "allOf": [ + {"if": {"properties": {"type": {"const": "file"}}}, "then": {"required": ["source"], "not": {"required": ["target"]}}}, + {"if": {"required": ["type"], "properties": {"type": {"const": "directory"}}}, "then": {"not": {"anyOf": [{"required": ["source"]}, {"required": ["target"]}]}}}, + {"if": {"required": ["type"], "properties": {"type": {"const": "symlink"}}}, "then": {"required": ["target"], "not": {"required": ["source"]}, "properties": {"mode": {"const": "0777"}}}} + ] + }, + "override": { + "type": "object", "additionalProperties": false, "required": ["operation", "paths", "expected_owner", "reason"], + "properties": { + "operation": {"enum": ["replace-file", "replace-symlink", "set-metadata", "change-type", "delete-path"]}, + "paths": {"type": "array", "minItems": 1, "uniqueItems": true, "items": {"$ref": "#/$defs/path"}}, + "expected_owner": {"type": "object", "additionalProperties": false, "required": ["layer"], "properties": {"layer": {"$ref": "#/$defs/id"}, "package": {"$ref": "#/$defs/packageName"}}}, + "reason": {"$ref": "#/$defs/nonempty"}, + "expected_sha256": {"type": "object", "propertyNames": {"$ref": "#/$defs/path"}, "additionalProperties": {"$ref": "#/$defs/digest"}}, + "metadata": {"type": "object", "additionalProperties": false, "minProperties": 1, "properties": {"mode": {"type": "string", "pattern": "^0?[0-7]{4}(?![\\s\\S])"}, "owner": {"$ref": "#/$defs/identity"}, "group": {"$ref": "#/$defs/identity"}}} + }, + "if": {"properties": {"operation": {"const": "set-metadata"}}}, + "then": {"required": ["metadata"]}, "else": {"not": {"required": ["metadata"]}} + }, + "action": { + "type": "object", "additionalProperties": false, "required": ["id", "phase", "adapter", "timeout_seconds", "network"], + "properties": { + "id": {"$ref": "#/$defs/localId"}, "phase": {"enum": ["build-local", "finalize", "deploy", "runtime"]}, + "adapter": {"$ref": "#/$defs/adapter"}, "argv": {"$ref": "#/$defs/strings"}, + "inputs": {"$ref": "#/$defs/strings"}, "outputs": {"$ref": "#/$defs/strings"}, "after": {"$ref": "#/$defs/localIds"}, + "timeout_seconds": {"type": "integer", "minimum": 1, "maximum": 9007199254740991}, + "required": {"type": "boolean", "default": true}, "network": {"enum": ["none", "allowed"]} + }, + "if": {"properties": {"phase": {"const": "finalize"}}}, "then": {"properties": {"network": {"const": "none"}}} + } + } +} diff --git a/spec/contract-registry.md b/spec/contract-registry.md new file mode 100644 index 0000000..df4fa7c --- /dev/null +++ b/spec/contract-registry.md @@ -0,0 +1,92 @@ +# Accepted contract registry + +[Русская версия](../ru/spec/contract-registry.md) + +**As of 2026-11-05. Coverage: D-001–D-074, RFC-0001–0011.** +This is the consolidated index of accepted contracts, not a new approval or an +implementation claim. `C-xxx` identifiers are stable navigation keys; `D-xxx` +remain the approval/history identifiers. All entries below are **Accepted**, with +the explicitly limited scope shown. A frozen format is identified separately. + +## Authority and interpretation + +- [Decision log](decision-log.md) records approval and subsequent refinements. + Linked RFCs and, where frozen, schemas define the normative contract. +- [Open questions](open-questions.md) track unresolved details. Accepted architecture + does not freeze every wire format, adapter or example mentioned in an RFC. +- D-061 ratifies RFC-0001–0007 with D-020–D-060. D-066–D-069 accept the subsequent + implementation contracts; D-070 freezes the Layer authoring format only. +- Read historical wording with later decisions: D-055 changes D-041 to zero/one + Purpose; D-056 makes D-017 fallback explicit and full-set atomic; D-057 removes + recovery as a support status; D-049 prohibits automatic rollback; D-036 narrows + D-032 account continuity; D-060 preserves native DynamicUser lifecycle. +- If documents conflict, report the conflict and resolve it explicitly. This index + does not independently override an RFC or silently close open questions. + +## Register + +| ID | Contract and accepted scope | Approval basis | Normative source | Remaining implementation boundary | +|---|---|---|---|---| +| C-001 | Platform boundaries: native OSTree objects/commits/refs/transport/deployments, existing Linux tools, ordinary filesystem/ELF execution, snapshot-pinned Arch OSTree. Archipelago owns semantic composition. | D-001, D-002, D-013, D-035 | [RFC-0001](../rfc/RFC-0001-architecture.md), [RFC-0003](../rfc/RFC-0003-build-and-composition.md), [RFC-0007](../rfc/RFC-0007-ostree-platform-integration.md) | Optional OSTree capabilities and concrete integration adapters require evidence. | +| C-002 | Independent immutable layer builds; Core starts with base + linux; composition produces one complete image. One effective owner per package; deterministic shared-dependency reassignment; indexed package payload comes from layer commits. | D-003, D-004, D-020, D-021, D-022, D-024, D-025, D-026, D-044 | [RFC-0002](../rfc/RFC-0002-layers-and-overlays.md), [RFC-0003](../rfc/RFC-0003-build-and-composition.md), [RFC-0008](../rfc/RFC-0008-manifests-locks-and-artifacts.md) | Complete artifact indexes, effective DB implementation and conformance fixtures. | +| C-003 | Exactly one Core, zero/one Purpose; Desktop/Server/IoT roles and concrete variants. Official Core-only is supported; custom overlays do not gain support automatically. Hardware adaptation uses overlays/profiles, not a separate Hardware Layer. Purpose changes preserve data. | D-007, D-008, D-009, D-041, D-055 | [RFC-0002](../rfc/RFC-0002-layers-and-overlays.md), [RFC-0008](../rfc/RFC-0008-manifests-locks-and-artifacts.md) | Exact desktop contents, services, DM and native onboarding adapters. | +| C-004 | Explicit overlay order and compatibility checks; no implicit dependency insertion/reordering. Scoped file/type/metadata overrides, ownership checks and provenance. Whole-package replacement is separate; unrestricted overwrite and standalone lower-package removal are excluded. | D-010, D-038, D-039, D-040, D-054 | [RFC-0002](../rfc/RFC-0002-layers-and-overlays.md), [RFC-0008](../rfc/RFC-0008-manifests-locks-and-artifacts.md) | Engine validation, effective-record transformations and filesystem fixtures. | +| C-005 | Git-authored inputs; manifest intent separate from exact locks; one immutable ordered Arch + Archipelago snapshot per composition. Content identities, checksums and provenance; URLs/dates are not identities; no silent build-time refresh. | D-005, D-023, D-042, D-043 | [RFC-0003](../rfc/RFC-0003-build-and-composition.md), [RFC-0008](../rfc/RFC-0008-manifests-locks-and-artifacts.md) | Executable Snapshot/SourceSet/lock schemas and full canonicalization evidence. | +| C-006 | Prefer binary packages; isolate source/package builds. DKMS binds to target kernel/ABI. Classify hooks/scriptlets across build/finalize/deploy/runtime; explicit deferred replacements; offline ordered finalization, depmod before initramfs; mandatory failures block publication even if pacman succeeds. | D-011, D-012, D-027, D-058, D-059 | [RFC-0003](../rfc/RFC-0003-build-and-composition.md), [RFC-0005](../rfc/RFC-0005-hooks-and-finalization.md) | Snapshot-specific adapters, ABI algorithm and execution/output evidence. | +| C-007 | Host Extensions use isolated base-plus-full-requested-set recomposition, pinned package names or retained local archives, matching package DB and durable generation history. No live /usr mutation. Reapply atomically; failures preserve state and inputs; fallback requires explicit choice. | D-014, D-017, D-018, D-037, D-056 | [RFC-0004](../rfc/RFC-0004-host-extensions.md), [RFC-0009](../rfc/RFC-0009-cli-contract.md) | Stable generation/request formats, all update/remove/restore workflows and package-action coverage. | +| C-008 | Support status describes the booted deployment and effective modifications. Applied Host Extensions are unsupported; pending/desired changes are separate. No recovery support status or guarantee of arbitrary local package compatibility. | D-015, D-016, D-057 | [RFC-0004](../rfc/RFC-0004-host-extensions.md) | Complete diagnostics and detection of out-of-band changes. | +| C-009 | Preserve persistent data across update/rebase/rollback/Purpose changes. One archipelago stateroot; Silverblue-style /var persistence; native deployment-local /etc and /usr/etc merge semantics. | D-019, D-030, D-032 | [RFC-0007](../rfc/RFC-0007-ostree-platform-integration.md) | Package persistence/migration adapters, especially /opt; no implicit global account sync. | +| C-010 | Standard sysusers/tmpfiles, preserve existing IDs, never merge build account DBs. Human-only explicit deletion; ambiguous/system identities cannot be deleted. Native DynamicUser remains native. Initial single-user onboarding precedes later deployments; rollback account edge case is explicit. | D-028, D-029, D-036, D-060 | [RFC-0006](../rfc/RFC-0006-system-accounts.md), [RFC-0007](../rfc/RFC-0007-ostree-platform-integration.md) | Reliable account classification and concrete reconciliation adapters. | +| C-011 | Per-image pacman-format DB at a non-default location; prevent live mutations. Retain base-matched extension working/history DBs independently of deployments. | D-031 | [RFC-0007](../rfc/RFC-0007-ostree-platform-integration.md), [RFC-0008](../rfc/RFC-0008-manifests-locks-and-artifacts.md) | Stable paths and fully validated DB construction/live-guard implementations. | +| C-012 | systemd-boot and staged deployments; retain booted, previous rollback, pending and pinned. Bounded per-boot checks gate cleanup. Target lifecycle only for service starts. Explicit rollback and separate reboot; no automatic boot-entry switch on failure. | D-033, D-034, D-046, D-047, D-048, D-049 | [RFC-0007](../rfc/RFC-0007-ostree-platform-integration.md), [RFC-0009](../rfc/RFC-0009-cli-contract.md) | General boot/storage profiles, success records, shutdown diagnostics and retention implementation. | +| C-013 | testing/stable publish the same verified immutable image on promotion. Both require full reproducibility and all functional gates. Core boot/login/extensions/overlays are inherited by each Purpose candidate, which adds service/session checks. Experiments remain private staging. | D-045, D-050, D-051, D-052 | [RFC-0003](../rfc/RFC-0003-build-and-composition.md), [RFC-0010](../rfc/RFC-0010-docker-build-and-distribution.md) | Reproducibility proof, complete validation matrix and trustworthy release attestations. | +| C-014 | Registries are initial architecture. Docker Compose + host cron, separated builder/KVM validator/publisher, monthly combined snapshots and daily pinned candidates. HTTP/native OSTree distribution, atomic signed channel discovery after full artifact verification; shared update/net-install/portal identities; purpose-separated OpenPGP keys. | D-006, D-063, D-068 | [RFC-0001](../rfc/RFC-0001-architecture.md), [RFC-0010](../rfc/RFC-0010-docker-build-and-distribution.md) | Deployment topology/URLs, key custody, exact schedules/quotas and worker isolation validation. | +| C-015 | RFC v0 architecture ratified; implement an end-to-end profile first without narrowing the architecture or weakening public gates. Primary binary and functional modules are Rust. | D-053, D-061, D-062 | [RFC-0001](../rfc/RFC-0001-architecture.md), [decision log](decision-log.md) | Delivery milestones are not claims of complete implementation or frozen module APIs. | +| C-016 | Installation/first-run control: live prepares storage/deployment; primary-user setup may occur on first installed boot. Core terminal onboarding, native desktop tools where feasible. Experimental x86_64 UEFI VM: GPT, FAT32 ESP, ext4 root, systemd-boot, no encryption/Secure Boot. | D-064, D-065 | [RFC-0006](../rfc/RFC-0006-system-accounts.md), [RFC-0007](../rfc/RFC-0007-ostree-platform-integration.md) | General installer schemas, native desktop adapters and broader hardware/storage profiles. | +| C-017 | Strict YAML/JSON intent model; canonical JSON/SHA-256 identities; separate LayerLock/CompositionLock; per-package OSTree payload and original/effective ALPM records with transformation provenance. | D-066 | [RFC-0008](../rfc/RFC-0008-manifests-locks-and-artifacts.md) | Layer authoring is frozen by C-020; remaining lock/artifact schemas, canonicalization and DB adapters still need conformance evidence. | +| C-018 | Unified CLI across builder/host/live; complete command catalog, capabilities, checked plan/apply under lock, JSON/errors and durable operations, phase-aware cancellation/resume, desired/pending/booted separation; initially no mandatory daemon. | D-067 | [RFC-0009](../rfc/RFC-0009-cli-contract.md) | Incremental command/backend implementation; accepted catalog is not an advertised binary capability list. | +| C-019 | Mandatory base/linux/Core and complete KDE/GNOME runtime/build-context action coverage; inspect no-action packages too. Shared policy/ledger/adapters and hooks CLI; zero unresolved mandatory actions plus functional evidence. Approved phased implementation plan. | D-069 | [RFC-0011](../rfc/RFC-0011-package-actions-compatibility.md), [plan](package-actions-plan.md) | Exact desktop manifests, supported snapshot transitions and complete execution evidence. | +| C-020 | **Frozen Layer YAML/JSON v1**: Core/Purpose/Overlay envelope, packages, runtime/provisioner inheritance, checks, actions, files, bounded overrides, compatibility/replacements, kernel/ABI references and strict validation. Changes require approval and schema versioning. | D-070 | [Schema](../schemas/layer-v1.schema.json), [validation](../schemas/README.md), [freeze record](layer-yaml-freeze.md) | Production Rust parser, full semantic validation, ABI algorithm and exact desktop contents; Composition/lock/artifact formats are not frozen by D-070. | + +### C-021 — Terra deployment and desktop update direction + +**Accepted: D-071.** [Deployment binding](terra-infrastructure.md): Core/Purpose YAML +and infrastructure repositories in git.fasoley.net/Archipelago; builders, validators, +registry and portal on terra beside `/opt/mirror`, with standalone deployment files. +Homepage/ISO/OSTree base is `https://mirror.nw-sys.ru/archipelago/`. Build exact YAML +revisions against pinned inputs, compose from registry layer commits, then make ISO. +Material You-inspired homepage with independent Arch Linux attribution. Registry-backed +CLI updates precede PackageKit/GNOME Software/KDE Discover integration. +Remaining boundaries: lock/release schemas, trust custody, worker isolation, pipeline +and update implementation and their evidence. C-013/C-014 public gates still apply. + +**Refinements: D-072/D-073.** Separate `tank/archipelago`, at most three monthly +snapshots with retained-input protection; capture and bulk copying deferred during +experimental live-mirror builds. Exact per-run evidence remains required. + +### C-022 — Daily experimental Core and base firmware + +**Accepted: D-074.** Daily Core candidates from current sources and the live mirror, +to exercise infrastructure and updates by image commit. Explicit `linux-firmware` +in Core and the live installer, with its dependency closure. Public gates remain; +hardware-wide support, reproducibility and update success need separate evidence. + +## Implementation and evidence + +Implementation status is independent of contract approval. Evidence lives in the +component documentation and lab records, not in an inferred Accepted → implemented +transition. Workspace paths: `test-lab/CORE-ISO-RESULTS.md`, `system/EXTENSIONS.md`, +`builder/HOOK-REVIEW.md`, `installer/CONTROL-LAYER.md`, `manifests/CORE-EXPERIMENT.md`. +Inspect their recorded run/commit/input identities before claiming conformance. +In particular, schema fixtures, experimental ISO success and one DKMS module do not +prove full desktop coverage, general hardware support or public release readiness. + +## Maintenance + +When a contract is explicitly approved or refined, update the RFC/schema as needed, +decision log, this registry (both languages), open questions and affected examples. +Keep C IDs stable; record replacement/refinement links instead of silently rewriting +history. New proposals remain in draft/review documents until approved. Add a row +when a new independently identifiable contract is accepted; use existing rows for +refinements. This register covers every accepted D-001–D-074 at least once; overlapping +references are intentional. No new architectural decision is created by indexing them. diff --git a/spec/contracts-v1-review.md b/spec/contracts-v1-review.md new file mode 100644 index 0000000..0dd36cc --- /dev/null +++ b/spec/contracts-v1-review.md @@ -0,0 +1,74 @@ +# Contract package review: manifests, CLI and infrastructure + +**Status: Approved.** D-066–D-069 and the package-action implementation plan +accepted 2026-11-04. See the complete [contract registry](contract-registry.md). +Explicitly open implementation details remain open, including +exact desktop manifests and the supported snapshot transition matrix. +Layer authoring syntax was subsequently frozen by D-070; see +[normative schema](../schemas/README.md). Composition/lock/artifact schemas remain separate. +RFC-0010 infrastructure/publication semantics are accepted; deployment bindings and +worker isolation validation remain pending. +RFC-0009 command coverage and operation lifecycle are accepted for incremental delivery. +Acceptance covers the RFC-0008 semantics recorded in D-066; concrete schemas, +adapters and implementation evidence remain pending. + +## Proposed decisions + +| ID | Document | Approval scope | +|---|---|---| +| D-066 | [RFC-0008](../rfc/RFC-0008-manifests-locks-and-artifacts.md) | Strict source model, two lock stages, canonical identities, indexed OSTree layer payload and effective/original ALPM accounting | +| D-067 | [RFC-0009](../rfc/RFC-0009-cli-contract.md) | Complete command matrix, capabilities, plan/apply, machine-readable results and lifecycle rules | +| D-068 | [RFC-0010](../rfc/RFC-0010-docker-build-and-distribution.md) | Docker Compose + cron, snapshot sealing, HTTP/native OSTree registry, release transaction, net install and ISO portal | +| D-069 | [RFC-0011](../rfc/RFC-0011-package-actions-compatibility.md) | Complete action coverage of base/linux/Core and locked KDE/GNOME closures; shared CLI policy and execution ledger | + +## Review questions before approval + +1. Approve reserved `archipelago/v1`, strict YAML/JSON and RFC 8785 identity, or + request a different serialization/versioning policy? +2. Approve per-package payload namespaces and deterministic effective ALPM records + with retained original records/deviation provenance? This is the main new + composition contract; its adapter still needs integration proof. +3. Approve the CLI matrix and no-daemon-first operation model, including explicit + `plan/apply`, separate package replacements and no automatic reboot/fallback? +4. Approve Docker Compose/host cron, separate worker/validator/publisher roles and + read-only HTTP registry, with native OSTree transport rather than OCI OS images? +5. Approve daily candidates/monthly snapshot policy, UTC and per-track serialization? + Exact cron expressions and worker quotas may be supplied with deployment bindings. +6. Phase one: enable only proven Core x86_64, or additionally nominate specific + GNOME/KDE/Server/IoT variants whose manifests/checks must be implemented first? +7. Approve the proposed purpose-separated OpenPGP trust/publication profile? + Real key custody, fingerprints, endpoints and TLS/auth configuration are deferred. +8. Approve the Core/KDE/GNOME package-action floor and phased + [implementation plan](package-actions-plan.md); confirm exact desktop manifests + and supported snapshot transitions before claiming complete coverage. + +## Remains outside blanket approval + +Concrete adapters for package scriptlets, system identities, persistent payload, +boot/cache integration; exact target-host Docker/nspawn capability profile; full +reproducibility evidence; unselected workload managers and desktop variants. +Public release gates D-050–D-052 are neither weakened nor considered passed. +Generated JSON Schemas and lock fixtures must be reviewed against the agreed field +semantics before the implementation declares v1 interoperability. + +## Verification plan + +- Parse source examples, verify relative references and status/decision consistency. +- Implement positive/negative schema and canonicalization vectors after approval. +- Exercise package ownership and ALPM metadata on two independently built layers. +- Test CLI capability claims, plan drift, cancellation/concurrency and error envelopes. +- Exercise publication crash points, stale metadata, missing objects and GC roots. +- Use one immutable release for offline install, net install, host update and portal. +- Prove build/validation worker boundaries and backup restore on the chosen hosts. + +## Delivery order after approval + +1. `contracts`: schemas, canonical hashing, indexes, lock validation and fixtures. +2. `builder/composer`: independent layer payloads, coherent ALPM DB and finalizers. +3. `cli/system/installer`: complete commands and transactions; update/net install. +4. `registry`: authenticated immutable fetch/publication and retention graph. +5. Docker/cron pipeline, snapshot adapter and static portal; private staging first. +6. Release reproducibility/functional proof, then eligibility for testing/stable. + +Infrastructure addresses and deployment topology can be supplied after semantic +approval; they are configuration, not a reason to embed placeholder domains in locks. diff --git a/spec/decision-log.md b/spec/decision-log.md index 8e2de41..2e10f9a 100644 --- a/spec/decision-log.md +++ b/spec/decision-log.md @@ -2,6 +2,8 @@ This file is the compact record of architectural decisions discussed by the RFC Committee. +For the current consolidated contract scope, see the [contract registry](contract-registry.md). + | ID | Decision | Status | |---|---|---| | D-001 | OSTree is the foundation for immutable filesystem storage, commits, refs, deployments, updates and rollback. | Accepted | @@ -65,6 +67,48 @@ This file is the compact record of architectural decisions discussed by the RFC | D-059 | Finalize aggregate schema, MIME, icon and library caches, vendor hwdb, selected distribution locales and distribution trust outputs against the composed image. Populate mutable font caches, system accounts/directories, machine-id and SSH host keys through the installed target lifecycle. Start services in the target deployment; declare initial defaults and preserve administrator enablement choices across updates. Machine-local trust, hwdb and linker configuration changes require corresponding cache regeneration integration. Reuse Arch/systemd tools; verify exact commands and paths against the pinned snapshot. Accepts these RFC-0005 action-family placements without freezing adapter/schema details. | Accepted | | D-060 | D-029's deletion prohibition applies to persistent system/service account records. Standard systemd DynamicUser= allocation and release remain normal service lifecycle, not Archipelago deletion of a persistent account. Do not introduce a custom identity lifecycle for these transient users. Accounts whose human-versus-system classification is ambiguous remain ineligible for deletion through Archipelago. | Accepted | | D-061 | RFC Committee approves RFC v0 (RFC-0001–0007) as an architectural contract on 2026-11-04, interpreted with D-020–D-060. Ratifies D-001–D-016 and D-018–D-019 with subsequent refinements. Explicitly open implementation contracts, formats, adapters, package database assembly, boot profile and reproducibility evidence remain to be agreed; illustrative examples are not stable APIs. Acceptance does not claim implementation or waive testing/stable release gates. Proceed sequentially through implementation contracts and code. | Accepted | +| D-062 | Implement the primary archipelago binary and functional modules in Rust. Laboratory tooling may use other languages; this does not freeze artifact schemas or FFI/adapter interfaces. | Accepted | +| D-063 | Plan monthly package repository snapshots, eventually created through ZFS on the mirror host. Defer that infrastructure until a bootable, working experimental archipelago-core-latest.iso exists. Snapshot identity and public testing/stable reproducibility requirements remain governed by D-043/D-050; a monthly label or latest filename does not replace immutable input identity. | Accepted | +| D-064 | Include installation and first-run control in the live/installed archipelago workflow: prepare target storage, install the system, and support deferred provisioning with primary-user creation on the first installed boot. Prefer native GNOME/KDE initial-setup tools where feasible; provide terminal CLI onboarding for Archipelago Core. Preserve D-036: create the primary user in the initial deployment before subsequent normal rollback targets. Exact disk profile, frontend adapters, completion/retry state and privilege/API contracts remain open. | Accepted | +| D-065 | Select the first experimental Core ISO profile: x86_64 UEFI VM, GPT with FAT32 ESP and ext4 root, systemd-boot, without encryption or Secure Boot. A separate /boot may be introduced if boot integration requires it. Acceptance exercises host-binary/nspawn ISO construction, live disk partitioning and installation of a viable OSTree deployment/bootloader, boot from the installed disk, first-run user provisioning and base services, then activation of a test Managed Overlay and a package Host Extension. Artifact schemas and package database adapters are experimental; public release gates remain unchanged. | Accepted | + +## Implementation contract drafts + +Each entry has its own approval status. D-066 was explicitly accepted on 2026-11-04; +D-067–D-069 and the package-action implementation plan were explicitly accepted +on 2026-11-04. Implementation and the explicitly open details remain pending. + +| ID | Decision | Status | +|---|---|---| +| D-066 | Accept strict YAML/JSON intent manifests, SHA-256 canonical JSON identities independent of transport, separate LayerLock/CompositionLock and indexed per-package OSTree payload with effective ALPM records, retained originals and explicit transformation provenance; see RFC-0008. Approved 2026-11-04; concrete schemas/adapters and implementation evidence remain pending. | Accepted | +| D-067 | Accept the unified CLI for build host, installed system and installer/live: complete command coverage, checked plan/apply under mutation locks, shared JSON/errors and durable operation records, phase-aware cancellation/resume, separate desired/pending/booted state, explicit reboot/rollback/fallback, capability reporting and initial operation without a mandatory daemon; see RFC-0009. Approved 2026-11-04; implementation is incremental. | Accepted | +| D-068 | Accept Docker Compose with host cron and separate builder/KVM validator/publisher roles, monthly immutable Arch + Archipelago snapshots and daily pinned candidate builds, HTTP/native OSTree distribution, complete verified artifacts before atomic signed channel updates, shared update/net-install/portal release identities, purpose-separated OpenPGP keys and same-image promotion. Core x86_64 is first after release gates; KDE/GNOME require independent acceptance. Deployment bindings, keys, exact schedules/limits and worker isolation validation remain pending; see RFC-0010. Approved 2026-11-04. | Accepted | +| D-069 | Accept mandatory action coverage for base/linux, Core integration packages and complete KDE/GNOME runtime closures, plus build dependencies in their build contexts; inventory scriptlets/hooks/helpers and no-action packages, shared versioned policy/adapters/result ledger and hooks CLI. Required failures block candidates even with pacman exit zero; readiness requires zero unresolved mandatory actions and functional evidence including desktop onboarding/session/services and inherited Core checks. Approve the phased implementation plan from inventory through publication gates. Exact desktop manifests and supported snapshot transitions require separate agreement; see RFC-0011 and spec/package-actions-plan.md. Approved 2026-11-04. | Accepted | + +## Layer schema freeze + +| ID | Decision | Status | +|---|---|---| +| D-070 | Freeze Layer YAML/JSON v1 after explicit block-by-block approval on 2026-11-04: envelope/packages, runtime/provisioner inheritance and check lifecycles, actions, files, bounded overrides, compatibility/replacements, exact kernel/ABI references and strict validation. Normative structural schema: schemas/layer-v1.schema.json; semantics: spec/layer-yaml-freeze.md and RFC-0008. Changes require separate approval and schema versioning. Complete desktop package sets, ABI algorithm, adapters, Composition/lock schemas and implementation evidence remain separate work. | Accepted | + +## Terra infrastructure binding + +| ID | Decision | Status | +|---|---|---| +| D-071 | Host Core/Purpose YAML source registries and infrastructure code at git.fasoley.net under Archipelago alongside rfc. Deploy registry, ISO/home portal and CLI-based layer/image/ISO builders on terra beside /opt/mirror, replacing superserv1 for new infrastructure work; retain standalone deployment files. Base URL is https://mirror.nw-sys.ru/archipelago/, with ISO and OSTree below it. Build from exact YAML revisions and pinned mirror inputs, publish layers, compose from the artifact repository, then build/publish ISO. Use Material You-inspired presentation and clear independent Arch Linux attribution. Implement registry-backed CLI updates, then plan PackageKit/GNOME Software/KDE Discover integration through the same staged transaction contract. D-068 release/trust gates remain; see spec/terra-infrastructure.md. Explicitly approved 2026-11-04. | Accepted | + +## Daily experimental Core and firmware + +| ID | Decision | Status | +|---|---|---| +| D-074 | Build experimental Core daily from current source commits and the current Arch mirror to exercise the infrastructure and commit-based OS updates end to end. A newly built image commit is an update candidate; unchanged commits are not new payload. Include linux-firmware explicitly in Core and the live installer, using its normal dependency closure rather than relying on linux to pull it. This does not claim every device is supported or all firmware has source available. D-073 snapshot deferral and D-050 public release gates remain. Explicit user direction, 2026-11-05. | Accepted | + +## Snapshot storage and experimental build sequencing + +| ID | Decision | Status | +|---|---|---| +| D-072 | Use a separate tank/archipelago ZFS dataset for future mirror captures, leaving the live mirror at /opt/mirror/data. Retain at most three monthly snapshots. This refines D-063/D-068 retention: referenced release/lock inputs cannot be silently destroyed to satisfy the cap; if no snapshot can be safely retired, capture must stop. User explicitly approved separate storage and the three-monthly-snapshot cap on 2026-11-05. Capture activation is subsequently deferred by D-073. | Accepted | +| D-073 | Defer snapshot creation and bulk mirror copying while the project matures. Use the live mirror for experimental image construction, prioritize reproducibility work and RFC conformance, and move to frozen snapshots for release construction later. Retain exact per-run input identities/checksums, reject changed or unavailable inputs rather than silently substituting them, and do not treat a mutable mirror or a successful experiment as a sealed Snapshot/public release. D-050 and public release gates remain. User explicitly directed this sequencing on 2026-11-05. | Accepted | ## Status guidance diff --git a/spec/layer-yaml-freeze.md b/spec/layer-yaml-freeze.md new file mode 100644 index 0000000..6e18a10 --- /dev/null +++ b/spec/layer-yaml-freeze.md @@ -0,0 +1,197 @@ +# Layer YAML v1 schema freeze review + +Status: Frozen by explicit user approval, 2026-11-04. Implements RFC-0008/D-066. +The normative structural schema is `../schemas/layer-v1.schema.json`; semantic +requirements below remain mandatory even where JSON Schema cannot express them. + +## Agreed: envelope and package requirements + +The user explicitly approved this block on 2026-11-04: + +- One `kind: Layer`, `apiVersion: archipelago/v1` for Core and Purpose. +- Required `metadata.name` (stable logical ID), `metadata.version` (SemVer), + `spec.type` and one `spec.architecture` per manifest. +- `spec.type` is `core` or `purpose` for this review; the accepted overlay type + remains part of RFC-0008 and is not removed by this scoped agreement. +- Purpose requires `spec.purpose: {role, variant}`; Core forbids it. + Roles: `desktop`, `server`, `iot`; variants include `gnome` and `kde`. +- `compatibility.core` constrains permitted Core logical IDs; omission imposes + no additional Core-ID restriction. +- `packages.runtime` and `packages.build` contain requirement objects with `name` + and optional `constraint`: one native libalpm comparison. Purpose declares its + own requirements; shared dependencies do not create duplicate payload ownership. +- Groups are expanded to explicit package names before use as manifest requirements. + Exact versions, providers, checksums and dependency closures belong in LayerLock. +- Snapshot selection occurs during resolve; mirror URLs and lower-layer commits + are not fields in this manifest block. +- Reject unknown fields, duplicate keys, anchors/aliases and implicit type coercion. + +Illustrative package lists do not approve complete Core/KDE/GNOME package sets. + +## Agreed: runtime declarations + +The user explicitly approved this block on 2026-11-04: + +- `runtime.sysusers`, `tmpfiles` and `presets` are optional lists of packaged + absolute `/usr` paths, defaulting to empty. Native systemd mechanisms run in + the target lifecycle; preserve existing identities and persistent data. Secrets + and machine account databases do not belong in manifests. +- `runtime.units` is an optional list of `{name, activation}`. `enable` requests + initial enablement, `socket` requests initial enablement of the named `.socket`, + and `manual` requests no automatic enablement. These are initial defaults; + administrator enablement survives updates. Conflicting presets/unit declarations + are validation errors. +- No separate `display_manager` field. Purpose declares the DM unit; its activation + adapter handles `display-manager.service`. DM changes require an explicit plan + accounting for the administrator's existing selection. +- Optional `runtime.provisioner` names a versioned adapter. Core supplies terminal + firstboot on tty1/ttyS0. A Purpose declaration replaces Core's provisioner; + omission inherits Core's. Onboarding finishes before subsequent normal deployments + and does not restart on updates. Example adapter names do not prove implementation. +- Optional `boot_checks` and `functional_checks` are action-ID lists, defaulting + to empty. Boot checks run with timeouts in the installed target's boot lifecycle. + Functional checks run only in isolated acceptance environments, not on every + user boot. Purpose inherits all Core checks and may add its own. +- Official validation profiles enforce completeness of mandatory declarations even + though these lists are syntactically optional. + +## Agreed: actions + +The user explicitly approved this block on 2026-11-04: + +- Required fields: locally unique `id`, `phase`, versioned `adapter`, positive + integer `timeout_seconds`, explicit `network` (`none` or `allowed`). +- Phases: `build-local`, `finalize`, `deploy`, `runtime`. Finalization requires + `network: none`. Exact adapter identities are locked. +- `argv`, `inputs`, `outputs`, `after` default to empty lists; `required` defaults + to true. No implicit shell interpolation. Adapters validate resource types, + allowed values and sufficient inputs. +- Phase selects execution context, not an automatic invocation. Workflows or + runtime references select invocation points. Functional checks can exercise + runtime behavior inside acceptance VMs without becoming boot checks. +- `after` references local action IDs. Composed identity is the pair of layer ID + and action ID. Cross-layer system ordering belongs to the finalizer adapter DAG, + including depmod before mkinitcpio. +- Cycles, missing references, incompatible phases and undeclared conflicting + outputs are errors. Required failures block the operation; boot failures report + diagnostics without automatic rollback/reboot. Official validation profiles + cannot have essential checks downgraded to optional. +- Package hooks/scriptlets are inventoried through PackageActionPolicy rather + than requiring every action to be manually repeated in the Layer manifest. + +## Final validation agreement + +The user approved the final block and froze Layer v1 on 2026-11-04: + +- One UTF-8 YAML document, no unknown fields, duplicate keys, anchors/aliases, + merge keys, custom tags, interpolation or implicit type coercion. Null does not + substitute for omission. Optional lists/maps use agreed empty defaults. +- Action IDs and Purpose variants match `[a-z0-9][a-z0-9._-]*`, at most 128 characters. +- Reject duplicate package requirements, action IDs, unit names and normalized + file paths. Resolve all action/source/adapter references; unknown adapters are + unsupported capabilities, not no-ops. +- Validate separately: structural schema; resolve/build dependencies, identities, + ownership and actions; complete composition conflicts, replacements, effective + package DB, kernel/ABI and finalization. Syntax validity is not readiness. +- Changes to fields or semantics require separate approval and schema versioning. + Exact desktop sets and adapter implementations remain separate work. + +## Agreed: file contributions + +The user explicitly approved this block on 2026-11-04: + +- `spec.files` defaults to an empty list. Each entry has `type` (`file` by + default, `directory` or `symlink`) and required `path`, `mode`, `owner`, `group`. +- Files require `source` and forbid `target`; symlinks require literal `target` + and forbid `source`; directories have neither. Directory entries never imply + recursive copying: every contributed object is explicit. +- `source` is relative to the locked source tree. Parent traversal and escape + through symlinks are forbidden. +- `mode` is an octal string. Symlink mode is `"0777"` under Linux semantics; + applying it never changes target permissions. +- Owners/groups are root or declared system identities; numeric resolution is + locked and unresolved immutable-payload ownership blocks the build. +- `/etc` contributions become `/usr/etc` vendor defaults with native installed + OSTree merge. Persistent-state contributions need explicit adapters; tmpfiles + normally creates target directories. `/boot` and ESP use the boot adapter. +- Symlinks are objects and are not followed when applying files or overrides. + A file declaration does not grant overwrite permission: conflicts require + explicit bounded overrides with expected ownership and reason. + +## Agreed: overrides + +The user explicitly approved this block on 2026-11-04: + +- `spec.overrides` defaults to empty and uses the same format for Purpose and + Managed Overlays. Each entry requires `operation`, a nonempty finite `paths` + list, `expected_owner.layer` and a nonempty `reason`. No glob or implicit recursion. +- Operations: `replace-file`, `replace-symlink`, `set-metadata`, `change-type`, + `delete-path`. Replacement/type-change paths require matching new `files` + objects. Deletion has no replacement; metadata changes affect only declared fields. +- `expected_owner.package` is required for package objects and absent for + layer-authored objects. Check ownership against the composition index immediately + before the operation; a mismatch is an error. +- `set-metadata` requires a nonempty `metadata` map containing only `mode`, + `owner`, `group`. xattrs/ACL/capability editing needs a separate schema extension. +- Directory deletion enumerates affected children explicitly. Bulk file deletion + cannot substitute for package removal. Overrides affect the new image, never + delete persistent state and never bypass `/etc`, boot or ESP contracts. +- Preserve changes in diff/provenance and effective package records. +- Optional `expected_sha256` maps affected paths to `sha256:<64 lowercase hex>` + digests of ordinary-file bytes. Keys must belong to `paths`. Reject this check + for symlinks and directories until their identity semantics are separately defined. + +## Agreed: compatibility and package replacements + +The user explicitly approved this block on 2026-11-04: + +- `compatibility.core` is allowed for Purpose/Overlay; `purpose` for Overlay only; + `requires`/`conflicts` for Purpose/Overlay; `before`/`after` for Overlay only. + Reject these fields on other layer types. Lists default to empty; duplicates + are forbidden. A nonempty Purpose allowlist requires a matching present Purpose. +- `requires`/`conflicts` reference Overlay IDs. Required overlays must already be + present, never auto-added. `before`/`after` constrain present overlays; require + presence separately through `requires`. Missing dependencies, conflicts and + cycles fail; composition order is never automatically repaired. +- Core/Purpose versions are not pinned here: CompositionLock records exact commits, + while package/ABI compatibility is checked separately. Concrete + `compatibility.kernel` structure remains pending. +- `packages.replacements` defaults to empty and is allowed for Purpose/Overlay, + forbidden for Core. Each entry requires `target`, `replacement`, `expected_owner` + (effective owning layer ID), and `reason`. +- Replacement must also be an explicit runtime requirement. Target absence or + owner mismatch fails. Replace the whole package and validate dependencies, + file conflicts and ABI of the complete result. Native pacman `replaces` does + not authorize this operation. Package replacement and file overrides are distinct. + +## Agreed: kernel binding + +The user explicitly approved this block on 2026-11-04: + +```yaml +compatibility: + kernel: + package: + name: linux + version: "" + architecture: x86_64 + archive_sha256: "sha256:<64 lowercase hex>" + release: "" + abi: + adapter: linux-module-abi/v1 + digest: "sha256:<64 lowercase hex>" +``` + +- Optional `kernel` permits one binding per layer. If present, every shown field + is required. Package identity is exact; release identifies `/usr/lib/modules/`. +- A versioned adapter defines ABI inputs and computes the digest; its exact code + identity is locked. Validate all declared values against pinned artifacts. + Package/architecture/release/ABI mismatch blocks composition. +- Absence means no declared kernel-bound payload, not compatibility with every + kernel. Detected modules without binding are errors. Ordinary Purpose layers + need no binding. Core supplying the kernel is not a dependency on a lower kernel. +- DKMS sources are distinct from prebuilt modules: finalization binds their build + to the selected kernel and validates the resulting modules. +- The ABI-reference structure is agreed; the concrete `linux-module-abi/v1` + algorithm still requires specification and validation before use. The example + adapter name does not establish implementation. diff --git a/spec/open-questions.md b/spec/open-questions.md index eedf30a..902834b 100644 --- a/spec/open-questions.md +++ b/spec/open-questions.md @@ -10,8 +10,39 @@ RFC v0 is accepted as an architectural contract under D-061. The implementation gates. Explicitly open choices still require agreement before the corresponding implementation becomes stable; numbered questions retain their IDs. +## Draft implementation proposals under review + +RFC-0008/D-066 was accepted on 2026-11-04 for manifest/lock/identity and +per-package payload/effective ALPM semantics. Concrete schemas and adapters remain +open. RFC-0009/D-067 command coverage and operation lifecycle were accepted on +2026-11-04; implementation and validation remain pending. +RFC-0010/D-068 infrastructure and publication semantics were accepted on 2026-11-04; +deployment bindings and worker isolation validation remain open. +RFC-0011/D-069 and its phased plan were accepted on 2026-11-04; exact desktop +manifests, supported snapshot transitions and adapter evidence remain pending. +The numbered questions below +retain their implementation details; [approval review](contracts-v1-review.md) +tracks the choices. + +- RFC-0008 addresses manifests/locks/indexes/identity and ALPM accounting (1–8, + 19, 46–47, 50–55, 61–62). Executable schemas and adapter proof still follow approval. +- RFC-0009 addresses CLI, plan/apply, lifecycle/state and capabilities (29–36, + 41–45, 57, 65, 68–69, 72). +- RFC-0010 addresses Docker/cron, snapshots, HTTP/native OSTree transport, trust, + publication, net install and portal (15–22, 26, 66, 70–71). Deployment URLs, + worker capability profile and exact schedules will be supplied later. +- RFC-0011 specifies the requested minimum scriptlet/hook scope: base/linux/Core + plus complete approved KDE/GNOME closures (52–56, 70–72). Exact desktop sets and + transition matrix need review; [implementation plan](package-actions-plan.md) + separates inventory, policy, adapters, execution evidence and pipeline gates. + ## Layer and composition model +D-070 freezes the Layer authoring schema and source-local rules discussed in +questions 2, 4, 5, 41, 49 and 55: see [schema](../schemas/README.md) and +[freeze record](layer-yaml-freeze.md). Their Composition/lock/artifact schemas, +runtime evidence and adapters remain open where explicitly noted below. + 1. D-044 selects separate payload and metadata namespaces inside a layer commit. What exact namespace names, schema and serialization define the stable artifact format? `payload/` and `metadata/` are illustrative names. 2. D-055 requires exactly one Core and zero or one Purpose; Archipelago Core ships with zero Purpose layers. How are optional Purpose selection and compatibility expressed in the schema and management interface? 3. What dependency solver semantics are required: version ranges, feature constraints, architecture constraints and conflict declarations? @@ -38,10 +69,19 @@ corresponding implementation becomes stable; numbered questions retain their IDs ## Build and registries +D-071 supplies deployment bindings for questions 15, 16 and 22: Git at +git.fasoley.net/Archipelago, terra beside `/opt/mirror`, native HTTP OSTree and +ISO/home portal under `/archipelago/`, with standalone files. See +[deployment direction](terra-infrastructure.md). Concrete lock/release wire schemas, +key custody/fingerprints, quotas/schedules, snapshot capture and worker isolation +remain open; these bindings alone do not complete the pipeline or update client. + 15. Which Git hosting and CI implementation is targeted first? 16. Which OSTree transport and registry server implementation is selected? 17. How are registry authentication, signing keys, trust roots and key rotation managed? 18. Which package repositories and Arch Linux Archive snapshots are supported? + D-063 plans monthly ZFS-backed snapshots on the mirror host after the working + experimental Core ISO milestone. Exact capture, retention and publication protocols remain open. 19. D-042 separates manifest intent from resolved locked inputs, with explicit resolve/update and no silent substitution during build/compose. What exact lockfile schema records layers, snapshot, package identities, architecture and finalization inputs, and how are manifest/lock identities and compatibility validated? 20. What build cache key and invalidation contract is required? 21. How are OCI build environments represented, if adopted? @@ -49,8 +89,14 @@ corresponding implementation becomes stable; numbered questions retain their IDs ## System and installer +D-064 selects deferred first-boot primary-user provisioning, Core CLI onboarding +and native GNOME/KDE setup where feasible. Question 57 retains the D-036 boundary; +question 72 tracks the remaining control-layer integration contract. + 23. D-033 selects systemd-boot initially. What exact UEFI/BLS, ESP/XBOOTLDR and packaged mkinitcpio integration profile is required? 24. Which filesystem and partition layout is the MVP default: ext4 or Btrfs, single root or separate state partitions? + D-065 selects GPT/FAT32 ESP/ext4 root for the first experimental x86_64 UEFI VM + ISO; a separate /boot is permitted if required. Production layout details remain open. 25. How are OSTree `/etc` three-way merges and configuration conflicts surfaced? 26. How are offline installation bundles structured? 27. How are LUKS2, TPM2 and Secure Boot sequenced in the roadmap? @@ -95,6 +141,10 @@ corresponding implementation becomes stable; numbered questions retain their IDs package inclusion and final pacman database construction remain open. 47. D-023 requires one common snapshot; D-043 defines an immutable ordered Arch plus Archipelago repository set, target architecture, database checksums and package identities, identified by a content-derived snapshot_id. Exact descriptor schema, canonicalization, verification and trust metadata remain open. 48. Which packages supplement `base` plus `linux` in Core to provide firmware, initramfs and OSTree boot/deployment integration (D-021)? + D-074 resolves baseline firmware: explicit `linux-firmware` and its dependency + closure in Core/live installer. Remaining integration inputs and hardware evidence + stay open. D-072/D-073 defer monthly snapshots (eventual cap: three) while D-074 + requests daily experimental Core from current sources/live mirror. 49. D-041 distinguishes role and concrete variant; D-055 revises cardinality to zero or one Purpose, including later selection from Archipelago Core. Multiple desktops may be expressed through a designed variant or Managed Overlay. DM selection, systemd switching and other desktop integration belong to the concrete Purpose contract. What exact schema expresses role, variant and overlay compatibility? Concrete Purpose contents/lifecycle policies and review of custom sets for official adoption remain separate design tasks. 50. When upper layers replace packages or shared libraries, how are dependencies of the complete resulting composition revalidated and incompatible replacements rejected? D-038 requires explicit whole-package replacement intent and validation of @@ -148,3 +198,8 @@ The baseline and deletion policy are accepted as D-028/D-029; see 71. D-051 defines minimum public-channel functional gates: Core boot/local login, Host Extension package installation and Managed Overlay application, and declared Purpose service functionality in a clean environment. Which package/overlay fixtures, supported VM/hardware profiles, service-specific probes and automated harness implement these gates? Functional tests do not replace question 70's reproducibility evidence. D-052 requires every Core gate to run against each complete Core + Purpose release candidate, in addition to its Purpose-specific service checks. +72. How does the live installer hand off to first-boot provisioning (D-064): target + identity and interrupted disk operations, context detection, frontend selection, + local console ownership, privilege boundaries, completion evidence, retries and + serialization with deployment preparation? How are native GNOME/KDE setup sessions + integrated without repeating account creation when adding Purpose to configured Core? diff --git a/spec/package-actions-plan.md b/spec/package-actions-plan.md new file mode 100644 index 0000000..7baf167 --- /dev/null +++ b/spec/package-actions-plan.md @@ -0,0 +1,96 @@ +# Package-action implementation plan + +**Status: Accepted — D-069, 2026-11-04.** Approved phased plan for RFC-0011; +no public-release authorization or claim that current adapters satisfy it. +Exact desktop manifests and supported snapshot transitions remain to be agreed. + +## Existing implementation + +Experimental Core boot/install/onboarding/overlay/nano passed VM tests; the user +reported successful manual testing. Repository-backed extensions are under test. +Current adapters capture Core hook hashes and inspect incoming actions; failure +detection partly uses log text. This is not complete version-aware action coverage +or proven KDE/GNOME setup/session support. + +## Responsibilities + +| Component | Work | +|---|---| +| `contracts` | Rust types/schemas: ActionInventory, PackageActionPolicy, CoverageReport, ActionResult; canonical identities | +| `builder` | Archive/root inventory, libalpm transaction adapter, build actions and ledger | +| `composer` | Finalizer DAG, output ownership, deterministic regeneration and coverage gate | +| `system` | Runtime units, extension/update integration, deployment/boot-bound results | +| `installer` | Deployment/boot actions and native/terminal provisioning adapters | +| `cli` | Hooks commands, shared JSON/errors, progress and diagnostics | +| `manifests` | Exact Core/KDE/GNOME packages, runtime expectations and policy references | +| `registry` | Policies and attestations bound to release/input identities | +| `test-lab` | Isolated fixtures, transition/failure matrix and desktop VM tests | + +Rust is primary; shell helpers may remain explicit pinned snapshot adapters. Do not +create a second Bash policy engine, dependency solver or hook-trigger implementation. + +## P0 — Freeze the minimum sets + +Review explicit Core/KDE/GNOME manifests, DM/onboarding/session and essential +integrations. Resolve runtime/build closures, versions/checksums and providers +against one snapshot. Output approved manifests, locks and functional profiles. +Gate: no mutable group membership or omission of essential actions. + +## P1 — Inventory without execution + +Implement archive + transaction-root inspection, `.INSTALL` functions, hook +precedence/overrides, helpers/conditions and explicit no-action entries. Dynamic +behavior remains reviewed, not inferred by running unclassified scripts. +Tests: missing archives, unsafe paths, shadowed hooks, helper drift and new hooks +affecting old files. Gate: deterministic accounting of every selected package. + +## P2 — Policy and coverage engine + +Implement Rust schemas/validation and `hooks explain/validate/coverage`. Check +phase/DAG/output contracts, timeout/network rules, mandatory flags and inapplicable +predicates. Tests: unknown/stale inputs, wrong snapshot, historical migrations, +mixed-phase functions and suppressed hooks without replacements. +Gate: unresolved mandatory actions cannot report success. + +## P3 — Ledger and Core adapters + +Integrate native libalpm ordering/NeedsTargets with actual action outcomes and output +validation. Pacman exit zero cannot override failed ledger entries. Verify Core +kernel/depmod/mkinitcpio, linker/locale/trust, hwdb/catalog, sysusers/tmpfiles, +service lifecycle, keyring and machine identity actions. Explicitly adapt mixed-phase +scripts; finalize the complete composition offline and record generated ownership. +Gate: Core fresh/transition tests and injected PostTransaction failure; no effects +on live host services, package DB, ESP or persistent state. + +## P4 — GNOME and KDE + +Inspect the additional complete closures: schema/GIO/GdkPixbuf, MIME/desktop/icons/ +fonts, trust, accounts/permissions and service defaults. Share common adapters; +DM/session/onboarding stays Purpose-specific. Resolve required persistence/UID/ +output-placement behavior before enabling release gates. +VM tests: clean installation, native setup or explicitly agreed adapter, real +graphical login/session, declared services, reboot without repeated setup, preserved +administrator choices, and inherited Core overlay/extension gates. +Gate: Core+GNOME and Core+KDE independently pass coverage and functionality. + +## P5 — Transitions and local composition + +Compare snapshot inventories; source/helper/trigger changes invalidate affected +evidence. Test upgrade branches, full-set extension reapplication, recomposition +removal, atomic staged replacement, rollback and runtime retries/ID/data retention. +Gate: required failure preserves booted/pending/rollback and retained local inputs; +no automatic partial fallback, stale global success marker or live mutation. + +## P6 — Infrastructure maintenance gate + +Docker/cron invokes the same CLI; publisher verifies coverage/tests bound to the +exact lock/policy. Unknown new actions leave a failed private run and the old public +release pointer. Retain policy history and diagnostics identifying source/adapter +owners. Test that a historical lock restores its exact policy/evidence. + +## Completion + +All three approved minimum profiles have zero unresolved mandatory actions, passing +action/full-system tests and supported snapshot transition coverage. Reproducibility +and other public gates remain separate. Optional external packages cannot substitute +for completing Core/KDE/GNOME support. diff --git a/spec/terra-infrastructure.md b/spec/terra-infrastructure.md new file mode 100644 index 0000000..aa7a5db --- /dev/null +++ b/spec/terra-infrastructure.md @@ -0,0 +1,107 @@ +# Terra deployment and desktop update integration + +[Русский обзор](../ru/spec/terra-infrastructure.md) + +**Status: Accepted deployment direction — D-071, 2026-11-04.** The user explicitly +authorized recording these requirements in RFCs and decision logs. Detailed release +wire schemas and GUI adapters still require implementation/review. + +## Source registries + +Git hosting: `https://git.fasoley.net/Archipelago/`, alongside `rfc`. +Repository bindings for the first deployment: + +- `core`: frozen Layer v1 YAML definitions of Arch Core. +- `purposes`: frozen Layer v1 YAML definitions of Purpose variants. +- `infrastructure`: Docker/cron, publishing, registry/portal and standalone deployment. + +These are source registries, not OSTree artifact repositories. Builds record exact +Git commits and source digests; a branch name is discovery, never a locked input. +Desktop examples remain disabled until exact sets and their acceptance are agreed. +Infrastructure source is also checked out on terra, not only in an agent workspace. + +## Host and routes + +`terra` replaces `superserv1` for new infrastructure builds, validation and publishing. +Existing laboratory runs on superserv1 may finish; their evidence is retained. +The Arch mirror already operates at `/opt/mirror` on terra. Integration into its +stack is permitted, and a complete standalone deployment must also be supplied. + +Public base: `https://mirror.nw-sys.ru/archipelago/`. + +| Relative route | Purpose | +|---|---| +| `/` | Project homepage and ISO portal | +| `iso/` | Immutable eligible ISO artifacts/checksums/signatures | +| `ostree/layers/` | Native OSTree archive repository for layer artifacts | +| `ostree/images/` | Native OSTree archive repository for complete deployable images | +| `v1/` | Pinned metadata, release/channel discovery and other RFC-0010 namespaces | + +Paths are deployment bindings. Consumers must retain the `/archipelago/` prefix. +Private staging is a separate access-controlled service/storage root, not a hidden +directory under the public static root. No unvalidated experimental ISO is promoted +merely because the homepage is public. Existing Arch mirror routes remain operational. + +## Builder and publication + +Use the archipelago CLI to resolve YAML registries plus pinned mirror inputs, +construct layer artifacts, upload them to the artifact repository, compose an image +from exact repository commits, then construct an ISO from that image and publish it. +Do not regenerate managed layers by silently reinstalling packages during composition. +Retain the D-068 split between builder, KVM validator and publisher, exact inputs, +offline finalization and immutable publication before an atomic signed channel update. +The current monolithic experimental ISO builder is not this completed pipeline. + +Cron, snapshots, public release gates and signing requirements remain D-063/D-068. +The mirror is transport, not snapshot identity. Physical dataset selection, storage +quotas, secret custody and reproducibility proof remain deployment/implementation work. + +### Current sequencing (D-072/D-073) + +The active mirror uses `/opt/mirror/data` on Btrfs; `tank/mirror` is a separate copy. +D-072 chooses a separate `tank/archipelago` ZFS dataset for future captures and caps +retention at **three monthly snapshots**. Referenced release/lock inputs must remain +available; if none can be safely retired, stop before creating a fourth snapshot. +Snapshot count does not itself prove a byte quota or bound retained build caches. + +D-073 subsequently defers snapshot creation and bulk mirror copying. Experimental +builds use the live mirror and record/verify exact per-run inputs; changed/missing +inputs are errors. Work on repeatable outputs and RFC conformance continues, but a +live mirror is not a sealed Snapshot. Frozen inputs and full gates remain necessary +for public release. The prepared capture tool is disabled; snapshot cron stays off. + +D-074 requests daily experimental Core construction from current source commits +and the live mirror to exercise build/distribution/update workflows. Changed image +commits become candidates for explicit host updates. Include `linux-firmware` as an +explicit Core and live-installer requirement, with the normal Arch dependency closure. +Do not infer that every device is supported or every firmware blob is open-source. +Daily candidate evidence does not authorize testing/stable publication. + +## Homepage + +Material You-inspired responsive presentation with an Arch-related visual identity, +project description, source/documentation links and verified ISO listings. Clearly +identify Archipelago as an independent distribution based on Arch Linux, with an +upstream link and trademark attribution; do not imply Arch Linux endorsement. +Use original artwork rather than assuming rights to modified upstream logos. +Planned or unvalidated variants have no active download links. + +## Updates and desktop frontends + +Implement registry-backed CLI update check/plan/apply first: authenticated discovery, +exact image/lock verification, plan preconditions under the mutation lock, atomic +full-set Host Extension reapplication, validation and native OSTree staging. Failures +preserve booted/pending state; activation requires explicit reboot. Custom composition +and managed-overlay intent must never be silently discarded by an official-base update. + +Then implement a PackageKit adapter and integration with GNOME Software and KDE +Discover (the software/update UI; KDE Store itself is a content marketplace). +The UI must present an OS-image update transaction, not run live `pacman -Syu` or +pretend independently selectable package updates are supported. UI and CLI share +planning, locks, progress, cancellation, errors, privilege checks and reboot-required +state. A failed extension reapplication cannot become an automatic clean-base fallback. + +GUI milestones: API/Polkit contract and capability mapping; PackageKit backend; +GNOME Software/Discover discovery and staging; reboot activation and failure tests +on both Purposes. PackageKit backend feasibility and need for frontend plugins must +be verified against selected package versions; no working GUI integration is implied.