From 0511f2e68f68ddb31766503c8f6ae0733b669a98 Mon Sep 17 00:00:00 2001 From: Tiberius Brastaviceanu Date: Thu, 6 Aug 2026 15:14:36 -0400 Subject: [PATCH 01/18] feat(ui): implement Group DNA service layer and update documentation Introduced a TypeScript service layer for Group DNA, replacing the GroupService stub with a callZome implementation. Updated group types and services to support new API functionalities. Enhanced documentation to include API references, architecture overviews, and test commands for Group DNA, ensuring clarity on the new structure and interactions within the system. --- Nondominium-game.dm | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Nondominium-game.dm diff --git a/Nondominium-game.dm b/Nondominium-game.dm new file mode 100644 index 0000000..e69de29 From e32ce800243ebf490e80053e2033000d315bc718 Mon Sep 17 00:00:00 2001 From: Tiberius Brastaviceanu Date: Thu, 6 Aug 2026 15:16:52 -0400 Subject: [PATCH 02/18] docs(requirements): introduce Source-NDO specifications and adaptive governance framework Added comprehensive documentation for the Source-NDO, a new ontological primitive representing generative ecological systems. This update includes the `source-ndo-requirements.md` detailing its role, governance patterns, and integration within the Nondominium architecture. Enhanced existing documents to reflect the necessity of the `vf:Source` ValueFlows extension and the adaptive governance loop for ecological systems. This change aims to clarify the framework for managing ecological commons and ensure accurate representation of environmental interactions within the economic information system. --- .../hREA/valueflows-1.0-compliance.md | 28 + documentation/implementation_plan.md | 105 +- documentation/requirements/governance.md | 57 + .../requirements/ndo_prima_materia.md | 24 +- .../requirements/post-mvp/Source-NDO.md | 1077 +++++++++++++++++ .../project-type-ndo-specifications.md | 22 + .../requirements/post-mvp/source-ndo-paper.md | 289 +++++ .../post-mvp/source-ndo-requirements.md | 450 +++++++ documentation/requirements/requirements.md | 1 + documentation/requirements/resources.md | 21 + documentation/zomes/resource_zome.md | 2 + pai/human_ai_collaboration.md | 677 +++++++++++ 12 files changed, 2731 insertions(+), 22 deletions(-) create mode 100644 documentation/requirements/post-mvp/Source-NDO.md create mode 100644 documentation/requirements/post-mvp/source-ndo-paper.md create mode 100644 documentation/requirements/post-mvp/source-ndo-requirements.md create mode 100644 pai/human_ai_collaboration.md diff --git a/documentation/hREA/valueflows-1.0-compliance.md b/documentation/hREA/valueflows-1.0-compliance.md index 679e94c..6e2d69a 100644 --- a/documentation/hREA/valueflows-1.0-compliance.md +++ b/documentation/hREA/valueflows-1.0-compliance.md @@ -491,6 +491,34 @@ These are not gaps but noteworthy observations for maintainers. - Add `primary_location: Option` (or `Option` if SpatialThing not yet implemented) +### P3 — Future (Nondominium-specific extensions beyond VF 1.0) + +**P3-1: `vf:Source` — Third flow endpoint primitive (Source-NDO)** + +ValueFlows 1.0 permits only `vf:Agent` and `vf:EconomicResource` as `provider` and `receiver` in economic events. The **Source-NDO** extension ([`source-ndo-requirements.md`](../requirements/post-mvp/source-ndo-requirements.md)) requires a third typed role: `vf:Source`. + +A `vf:Source` endpoint represents a generative ecological system (watershed, river, fishery, forest) that: +- **yields** economic resources when accessed (extraction events) +- **receives** ecological effects (loading/pollution events) +- **conditions** future events through a changing `SourceRegimeState` +- is **not ownable** and **not agentive** (neither `vf:Agent` nor `vf:EconomicResource` fits) + +**Proposed implementation:** + +``` +vf:Source rdfs:subClassOf owl:Thing + rdfs:comment "A generative ecological system that yields resources, + receives ecological effects, and conditions future + possibilities without being ownable or intentional." + +vf:EconomicEvent vf:fromSource vf:Source (extraction: Source as provider) +vf:EconomicEvent vf:toSource vf:Source (loading: Source as receiver) +``` + +**Impact:** Without this extension, Nondominium cannot express watershed governance, fishery commons, or any ecological commons under the `Nondominium` property regime without ontological fictions (false `primaryAccountable`, phantom `raise` events). This is a **Nondominium-proposed extension to ValueFlows 1.0**, not yet submitted to the VF working group. + +**Priority:** Required for Source-NDO implementation (post-MVP). Does not affect hREA 1.0 compliance score; should be tracked as a future contribution to the VF standard. + --- ## Appendix: Full Field Mapping Tables diff --git a/documentation/implementation_plan.md b/documentation/implementation_plan.md index 2c93e6c..e473be6 100644 --- a/documentation/implementation_plan.md +++ b/documentation/implementation_plan.md @@ -8,34 +8,97 @@ This plan details the phased implementation of the nondominium hApp, a decentral ### 1.1 Requirements map (normative sources) +This index is the entry point for phased delivery. **Current focus:** Layer 1 UI on the NDO detail view (`/ndo/:hash`) — **ResourceSpecification** (the shareable form), **GovernanceRule** (embedded rules governing agent–resource interaction), and **Process** readiness (what agents may do under those rules; Layer 2 / REQ-PROC-*). Layer 0 identity UI is implemented; Layer 1 activation (`NDOToSpecification`) and Layer 2 activation (`NDOToProcess`) are normative but not yet wired in DNA — UI work proceeds against existing MVP zome APIs plus prima materia REQ-NDO-L1-* / REQ-NDO-L2-* targets. Status cross-check: [IMPLEMENTATION_STATUS.md](IMPLEMENTATION_STATUS.md). + +#### Core normative (PRD, NDO model, UI, data model) + | Source | Role | |--------|------| -| [requirements.md](requirements/requirements.md) | PRD; REQ-USER-*, REQ-RES-*, REQ-GOV-*, REQ-PROC-*, REQ-AGENT-* (§4.4 post-MVP agent ontology) | -| [ndo_prima_materia.md](requirements/ndo_prima_materia.md) | NDO layers (L0/L1/L2), lifecycle and operational state, capability surface, COP framing; REQ-NDO-* (§9), migration (§10) | -| [ui_design.md](requirements/ui_design.md) | UI specifications (complements [specifications/ui_architecture.md](../specifications/ui_architecture.md)) | -| [post-mvp/unyt-integration.md](requirements/post-mvp/unyt-integration.md) | Unyt / RAVE / economic agreement slots (REQ-NDO-CS-07–CS-11) | -| [post-mvp/flowsta-integration.md](requirements/post-mvp/flowsta-integration.md) | Flowsta identity slots and Tier 1/2 governance (REQ-NDO-CS-12–CS-15) | -| [post-mvp/many-to-many-flows.md](requirements/post-mvp/many-to-many-flows.md) | N-ary custody and ValueFlows events; plan after shared custody / `AgentContext` model matures | -| [post-mvp/versioning.md](requirements/post-mvp/versioning.md) | Version DAG for resources and app-as-resource; complements REQ-NDO-L1-03 (multiple specs per NDO) | -| [post-mvp/digital-resource-integrity.md](requirements/post-mvp/digital-resource-integrity.md) | Manifests and verifiable digital assets; aligns with Layer 1 `DigitalAsset` capability slots (prima materia §9.2) | -| [post-mvp/resource-transport-flow-protocol.md](requirements/post-mvp/resource-transport-flow-protocol.md) | Multi-dimensional transport/flow semantics over economic events | -| [post-mvp/valueflows-dsl.md](requirements/post-mvp/valueflows-dsl.md) | DSL for recipes, bulk bootstrap, scripted coordination (operational tooling track) | -| [post-mvp/lobby-dna.md](requirements/post-mvp/lobby-dna.md) | Multi-network federation: Lobby DNA (public registry), Group DNA (per-group coordination), NDO DNA extensions (`NdoHardLink`, `Contribution`, `Agreement`); dual deployment (standalone + Moss applet) — REQ-LOBBY-*, REQ-GROUP-*, REQ-NDO-EXT-* | -| [archives/resources.md](archives/resources.md), [archives/governance.md](archives/governance.md) | Ontology and gap-analysis context (non-normative for REQ IDs) | +| [requirements.md](requirements/requirements.md) | PRD — REQ-USER-*, REQ-RES-*, REQ-GOV-*, REQ-PROC-*, REQ-AGENT-* (§4.4 post-MVP agent ontology); REQ-UI-* (§4.5 MVP UI) | +| [ndo_prima_materia.md](requirements/ndo_prima_materia.md) | NDO layers (L0/L1/L2), lifecycle vs operational state, capability surface; **REQ-NDO-L1-*** (§9.2), **REQ-NDO-L2-*** (§9.3), REQ-NDO-* (§9), migration (§10) | +| [ui_design.md](requirements/ui_design.md) | UI vision — MVP Layer 0 complete; NDO view tabs (Resources, Governance, Composition, Activity) stubbed for Layer 1+ content | +| [specifications/ui_architecture.md](specifications/ui_architecture.md) | Implemented UI stack, routes, stores, services (`resource.service.ts`, `governance.service.ts`), component map | +| [specifications/specifications.md](specifications/specifications.md) | Technical data structures — `ResourceSpecification`, `GovernanceRule`, `EconomicResource`, `EconomicProcess`, VfAction, cross-zome governance interface | + +#### Layer 1 — Specification (resource form) + +| Source | Role | +|--------|------| +| [zomes/resource_zome.md](zomes/resource_zome.md) | **Implemented** coordinator/integrity API — `ResourceSpecification`, `GovernanceRule`, `EconomicResource`; planned `NDOToSpecification` / `DigitalAsset` links | +| [requirements/resources.md](requirements/resources.md) | Resource ontology — implemented vs planned; Layer 1 activation gap; governance defaults from `PropertyRegime` × `ResourceNature` (non-normative REQ IDs) | +| [post-mvp/project-type-ndo-specifications.md](requirements/post-mvp/project-type-ndo-specifications.md) | Structured know-how bundles for project-type NDOs (OSHWA / Open Know-How → Layer 1 assets); lifecycle-matched completeness | +| [post-mvp/source-ndo-requirements.md](requirements/post-mvp/source-ndo-requirements.md) | **Source-NDO** — `Source` as third ontological primitive; `SourceProfile` Layer 0 extension; adaptive cybernetic governance loop; `vf:Source` ValueFlows extension (REQ-SOURCE-*) | +| [post-mvp/source-ndo-paper.md](requirements/post-mvp/source-ndo-paper.md) | Academic grounding: Occam's razor proof, river case study, Ostrom SES mapping (informative) | +| [post-mvp/versioning.md](requirements/post-mvp/versioning.md) | Version DAG — **REQ-NDO-L1-03** (multiple `ResourceSpecification` links per NDO identity) | +| [post-mvp/digital-resource-integrity.md](requirements/post-mvp/digital-resource-integrity.md) | Content-addressed manifests, composable verification — **REQ-NDO-L1-06** `DigitalAsset` capability slots (prima materia §9.2) | +| [post-mvp/fractal-composable-resource-architecture.md](requirements/post-mvp/fractal-composable-resource-architecture.md) | Archival design — atomic / component / composite nesting; informs integrity (R5–R6) and Composition tab (post-MVP) | + +#### Governance (embedded rules → operator enforcement) + +| Source | Role | +|--------|------| +| [requirements/governance.md](requirements/governance.md) | Governance ontology — governance-as-operator, PPR, validation, role tiers; gap analysis (non-normative REQ IDs) | +| [specifications/governance/governance-operator-architecture.md](specifications/governance/governance-operator-architecture.md) | **REQ-ARCH-07/09** — `GovernanceTransitionRequest` / `evaluate_state_transition`; rules on spec, enforcement in `zome_gouvernance` | +| [specifications/governance/governance-operator-implementation-guide.md](specifications/governance/governance-operator-implementation-guide.md) | Implementation patterns for rule evaluation and cross-zome calls | +| [specifications/governance/private-participation-receipt.md](specifications/governance/private-participation-receipt.md) | PPR categories and bilateral receipts — accountability after governed process completion | +| [zomes/governance_zome.md](zomes/governance_zome.md) | Coordinator API — commitments, events, claims, validation, PPR issuance | +| [post-mvp/unyt-integration.md](requirements/post-mvp/unyt-integration.md) | Typed **`EconomicAgreement`** governance rules, RAVE settlement (REQ-NDO-CS-07–CS-11) — Layer 1 rule family | +| [post-mvp/flowsta-integration.md](requirements/post-mvp/flowsta-integration.md) | **`IdentityVerification`** / `FlowstaIdentity` slots (REQ-NDO-CS-12–CS-15) — agent identity gates on high-trust transitions | + +#### Process (Layer 2 — what agents do with resources) + +| Source | Role | +|--------|------| +| [requirements.md §5](requirements/requirements.md) | **REQ-PROC-*** — Use, Transport, Storage, Repair; role-gated initiation; process validation and chaining | +| [ndo_prima_materia.md §4.4](requirements/ndo_prima_materia.md) | Layer 2 activation via `NDOToProcess`; hosts Commitments, Claims, EconomicEvents, PPRs (**REQ-NDO-L2-***) | +| [post-mvp/resource-transport-flow-protocol.md](requirements/post-mvp/resource-transport-flow-protocol.md) | Multi-dimensional transport/flow semantics (physical, custodial, value, legal, information) over **EconomicEvent** metadata — post-MVP | +| [post-mvp/many-to-many-flows.md](requirements/post-mvp/many-to-many-flows.md) | N-ary custody and multi-party events — after shared custody / `AgentContext` model matures | +| [post-mvp/valueflows-dsl.md](requirements/post-mvp/valueflows-dsl.md) | VF DSL for recipes, bulk bootstrap, scripted coordination — operational tooling track | + +#### Federation, agent context, and supplementary ontology + +| Source | Role | +|--------|------| +| [post-mvp/lobby-dna.md](requirements/post-mvp/lobby-dna.md) | Multi-network federation — Lobby / Group / NDO DNA extensions (REQ-LOBBY-*, REQ-GROUP-*, REQ-NDO-EXT-*) | +| [requirements/agent.md](requirements/agent.md) | Agent ontology — roles, affiliation, `AgentContext` (post-MVP); background for governance participation and process access | --- ## 2. Implementation Principles -- **Incremental Enhancement**: Build on existing working code without breaking changes, extending functionality through new modules and functions -- **ValueFlows Compliance**: All data structures and flows adhere to the ValueFlows standard with Economic Process integration -- **Agent-Centric Design**: All data and validation flows from the perspective of individual agents with capability progression -- **Progressive Trust**: Agents earn capabilities through validation (Simple → Accountable → Primary Accountable Agent) with PPR reputation tracking -- **Embedded Governance**: Rules and access control are enforced at the resource and agent level with Economic Process integration -- **Capability-Based Security**: All access is managed through Holochain capability tokens with role-based process access -- **Privacy-Preserving Accountability**: PPR system enables reputation without compromising privacy through selective disclosure -- **Process-Aware Infrastructure**: Economic Processes (Use, Transport, Storage, Repair) integrated throughout the system architecture -- **NDO alignment**: When implementing the NDO track, follow pay-as-you-grow **layer activation** (L0 identity always on; L1 specification and L2 process when complexity demands) and keep **LifecycleStage** (on identity) orthogonal to **OperationalState** (on resource instances), with the governance zome as state-transition operator (REQ-NDO-LC-02, REQ-NDO-OS-02) +Development follows **Complexity Driven Development (CDD)** and **Complexity Oriented Programming (COP)**: software as an evolving **coordination structure**, not a deterministic machine. The design unit is `agent → process → resource → relation → network`, not `function → class → module`. Methodology reference: [archives/complexity_oriented_programming.md](archives/complexity_oriented_programming.md); operational checklist: `.claude/skills/complexity-oriented-programming/SKILL.md`. + +Judge outcomes by **systemic viability** — anti-fragility, evolvability, coordination capacity, holonic health, trust composability — not only delivery speed or defect rate. + +### 2.1 CDD / COP foundations + +| Principle | Implementation requirement | +|-----------|---------------------------| +| **Dynamic complexity matching** | Match governance overhead and schema rigidity to *actual* social complexity — not the imagined maximum. Apply **subsidiarity**: resolve decisions at the most local level that can handle them (agent, group, NDO, network); escalate only when broader context is genuinely required. | +| **Progressive activation** | Artifacts begin as low-complexity intent and accrue structure over time. **Layer 0** identity always on; **Layer 1** specification and **Layer 2** process activate only when coordination demands it (REQ-NDO-L1-*, REQ-NDO-L2-*). UI and DNA must not force full spec/governance/process surfaces on `Ideation`-stage NDOs. | +| **Governance-as-operator** | Decouple the **data substrate** (`zome_resource`) from **regulatory signaling** (`zome_gouvernance`). Business and governance logic must not be hard-coded into core entry schemas; rules evolve as mutable data without destructive migrations (REQ-ARCH-07, REQ-ARCH-08). | +| **Stigmergic coordination** | Prefer discoverable traces, anchor links, reputation signals (PPRs), and **CapabilitySlot** attachments over central orchestrators. Agents coordinate by modifying a shared environment — the DHT — not by a mediating platform service. | +| **Fractal composability** | Use the same coordination primitives at agent, group, NDO, and federation scales. **Trust and integrity compose** through hierarchies (atomic → component → composite): local verification at each level yields global coherence; changes re-verify only affected paths (digital integrity, holonic NDO links — post-MVP). | +| **Path-dependency awareness** | Before refactors or major UI/API contracts, scan legacy choices (MVP orphan `ResourceSpecification` entries, localStorage group shells, stub tabs). Do not inherit constraints blindly — document migration windows (REQ-NDO-MIG-*) when Layer 1 UI bridges old and new models. | +| **Anti-fragility** | Disruption should teach, not only hurt. Disputes, validation failures, and adversarial behaviour must generate auditable signals (PPRs, validation receipts, governance events) that improve future coordination — not merely error screens. | + +### 2.2 Nondominium enactments + +- **Incremental enhancement**: Extend working code through new modules and functions; avoid breaking MVP flows until migration windows are defined. +- **ValueFlows compliance**: Data structures and flows adhere to ValueFlows — Knowledge (`ResourceSpecification`), Plan (`Commitment`), Observation (`EconomicEvent`, `Claim`) — with Economic Process integration (REQ-PROC-*). +- **Agent-centric design**: Data and validation originate on each agent's source chain; capability progression (Simple → Accountable → Primary Accountable) gates sensitive actions. Post-MVP: requirements must hold for holonic actors (`AgentContext`), not only individual `AgentPubKey`s (REQ-AGENT-01, REQ-GOV-16). +- **Resources as autonomous entities**: Resources carry embedded governance, stable identity (Layer 0), and lifecycle — they are coordination objects, not passive CRUD rows. **LifecycleStage** (identity maturity) stays orthogonal to **OperationalState** (instance process condition) (REQ-NDO-LC-02, REQ-NDO-OS-02, REQ-NDO-OS-04). +- **Embedded governance (Social DNA)**: `GovernanceRule` entries on Layer 1 `ResourceSpecification` define how agents may interact; the governance zome evaluates transitions against them. Rules are **mutable data** communities can amend; identity anchors are not. +- **Capability-based security**: Holochain capability tokens plus role-gated process access (REQ-SEC-01, REQ-SEC-02); field-level private data grants with expiry and explicit revocation. +- **Privacy-preserving accountability**: Bilateral PPRs and derivable `ReputationSummary` — user-sovereign, no global scoring aggregator (REQ-PPR-10, REQ-PPR-11). +- **Process-aware infrastructure**: Use, Transport, Storage, Repair processes are first-class; initiation, validation, and chaining follow embedded rules and role credentials (REQ-PROC-01–REQ-PROC-09). + +### 2.3 Layer 1 UI and cross-layer discipline + +- **Mirror the zome boundary in the UI**: Specification tab → data model (`ResourceSpecification`, assets, version links); Governance tab → embedded rules and their semantics; Activity / process surfaces → Layer 2 readiness gated by rules — do not collapse layers into a single undifferentiated form. +- **Complexity-matched affordances**: Expose creation/editing depth proportional to `LifecycleStage` and layer activation (e.g. lightweight spec at `Specification`, full governance editor when rules matter, process actions only when Layer 2 or MVP process APIs exist). +- **Service-layer contract stability**: UI calls Effect-TS services (`resource.service.ts`, `governance.service.ts`); zome function names and shared types (`@nondominium/shared-types`) are the integration seam — keep components free of raw zome payloads. +- **Correctness over cleverness**: Governance infrastructure for real economic relationships; a wrong validation rule on the DHT cannot be rolled back — prefer explicit, reviewable rule data over implicit UI magic. --- diff --git a/documentation/requirements/governance.md b/documentation/requirements/governance.md index 81135b6..ed2beec 100644 --- a/documentation/requirements/governance.md +++ b/documentation/requirements/governance.md @@ -317,6 +317,63 @@ The `AffiliationRecord` entry hash then becomes the evidence that the agent's `A **Traceability:** `ndo_prima_materia.md` **Section 11.6** (Flowsta integration in the requirements matrix). +### 3.8 Adaptive Governance for Source-NDOs (`source-ndo-requirements.md`) + +> **Status:** 🔄 **Post-MVP — designed.** No Rust implementation yet. See [`source-ndo-requirements.md`](post-mvp/source-ndo-requirements.md) for normative requirements; [`source-ndo-paper.md`](post-mvp/source-ndo-paper.md) for academic justification. + +**The governance-as-operator pattern meets complex ecological systems.** For project-type NDOs, governance rules are fixed at design time and evaluated on each transition request. For Source-NDOs — watersheds, rivers, fisheries, forests — rules must *adapt* as the source's condition changes. This is not a relaxation of governance rigor; it is a deeper application of it. + +**The cybernetic governance loop:** + +``` +Boundary events (extraction, discharge, restoration) + ↓ accumulated on Source Layer 0 hash as EconomicEvent entries +Ecological interpretation (scientists, stewards, monitoring systems) + ↓ update SourceProfile.regime_state, resilience, tipping_threshold +Governance rule adaptation (GovernanceRule entries revised or replaced) + ↓ evaluated by governance-as-operator on subsequent transition requests +Access affordances (extraction quotas, discharge limits, monitoring obligations) + ↓ condition future events +(loop) +``` + +This loop extends — but does not break — the governance-as-operator architecture. The governance zome still evaluates rules on transition requests; the new dimension is that rules can change via a validated rule-revision process (REQ-SOURCE-GOV-01), and the rule evaluation also reads `SourceProfile.regime_state` to apply precautionary blocks near `tipping_threshold` (REQ-SOURCE-GOV-03). + +**Black-box epistemics.** Unlike complicated resource governance (where rules can be fully specified from adequate knowledge), complex ecological governance must operate on partial information. The `complex_interior: true` flag on `SourceProfile` makes this epistemological stance machine-readable: the governance system governs observable peripheral events (what crosses the source boundary) rather than claiming to model the interior. This is Ashby's law of requisite variety applied to governance: the complexity of the governance system must match the complexity of the system it regulates — but for a complex system, matching that complexity means acknowledging and operating with irreducible uncertainty. + +**New governance concepts introduced:** + +| Concept | Description | +|---|---| +| **Adaptive rule revision** | GovernanceRules on Source-NDOs may be revised through a multi-validator governance process as ecological interpretation changes. Rule version history is preserved. | +| **Precautionary governance** | Events that would push current stock below `tipping_threshold` may be blocked or escalated to multi-validator review. | +| **Monitoring obligations** | Agents who extract from or discharge into a Source may be required to submit condition data as a precondition for continued access. | +| **Stewardship role** | A new functional role (`Steward`) carries obligations (monitoring, ledger maintenance, rule revision) without conferring property rights. No steward owns a Source-NDO. | +| **SourceRegimeState** | A machine-readable ecological condition classifier (`Pristine → Stable → Stressed → Degraded → Critical → Transformed`), governance-validated on transition. | + +**Ostrom's principles applied to Source governance.** Source-NDO governance implements all eight of Ostrom's design principles for commons governance (see §1.6 of this document), extending them to complex ecological systems: + +| Ostrom's principle | Source-NDO implementation | +|---|---| +| Clearly defined boundaries | Source boundaries (spatial, temporal, flow endpoints) defined at Layer 1 | +| Match rules to local conditions | `SourceRegimeState`-conditional rules; adaptive loop matches rules to current ecological condition | +| Collective choice arrangements | Multi-validator rule revision; steward community governance of `GovernanceRule` updates | +| Monitoring | Monitoring obligations as GovernanceRule type; event ledger as audit trail | +| Graduated sanctions | `regime_state`-dependent access restrictions; escalating precaution toward `tipping_threshold` | +| Conflict resolution | DisputeResolutionParticipation PPR category; existing NDO dispute mechanisms | +| Minimal recognition of rights | Holochain permissionless access; stewardship without ownership | +| Nested enterprises | Source hierarchy links (`yields`, `conditions`); watershed-level governance over river-level NDOs | + +**Relation to existing governance architecture.** Source-NDO governance does not introduce a new governance engine. It extends the existing governance-as-operator architecture with: +1. An additional evaluation input: `SourceProfile.regime_state` (cross-entry read by governance zome). +2. A new `GovernanceRule` class: monitoring obligation rules. +3. A rule-revision governance process: multi-validator approval required for GovernanceRule updates on Source-NDOs. +4. A new functional role: `Steward` (alongside the existing governance tiers). + +All existing mechanisms — PPRs, capability tokens, validation receipts, ValueFlows events — apply unchanged to Source-NDO interactions. + +**Traceability:** `source-ndo-requirements.md` §5 (REQ-SOURCE-GOV-01 through REQ-SOURCE-GOV-08). + --- ## 4. OVN Governance Ontology: 15 Years of Practice diff --git a/documentation/requirements/ndo_prima_materia.md b/documentation/requirements/ndo_prima_materia.md index 27b1a7b..0adcd73 100644 --- a/documentation/requirements/ndo_prima_materia.md +++ b/documentation/requirements/ndo_prima_materia.md @@ -4,7 +4,7 @@ **Created**: 2026-03-10 **Last updated**: 2026-06-16 **Authors**: Nondominium project -**Relates to**: `post-mvp/many-to-many-flows.md`, `post-mvp/ndo-versioning.md`, `post-mvp/digital-resource-integrity.md`, `post-mvp/unyt-integration.md`, `post-mvp/flowsta-integration.md`, `lobby-dna.md`, `post-mvp/project-type-ndo-specifications.md` +**Relates to**: `post-mvp/many-to-many-flows.md`, `post-mvp/ndo-versioning.md`, `post-mvp/digital-resource-integrity.md`, `post-mvp/unyt-integration.md`, `post-mvp/flowsta-integration.md`, `lobby-dna.md`, `post-mvp/project-type-ndo-specifications.md`, `post-mvp/source-ndo-requirements.md` **Implementation reference**: `documentation/IMPLEMENTATION_STATUS.md` (NDO Layer 0 ✅ PR #80; NDO DNA extensions ✅ PR #103; Layers 1 & 2 ❌) --- @@ -1590,6 +1590,28 @@ The Lobby layer connects to the NDO three-layer model at specific points: See `lobby-dna.md` for normative requirements (REQ-LOBBY-*, REQ-GROUP-*, REQ-NDO-EXT-*) and `specifications/post-mvp/lobby-architecture.md` for full schema, coordinator APIs, pipelines, UI, Moss contract, and 7 ADRs. +### 11.8 Source-NDO Integration + +> **Status:** 🔄 **Post-MVP — designed.** No Rust implementation yet. Normative requirements in [`source-ndo-requirements.md`](post-mvp/source-ndo-requirements.md). Academic justification in [`source-ndo-paper.md`](post-mvp/source-ndo-paper.md). + +Source-NDO introduces `Source` as a third ontological primitive — neither Agent nor Resource — to represent generative ecological systems (watersheds, rivers, forests, fisheries) and knowledge commons that yield resources, receive ecological effects, and condition future possibilities without being ownable or intentional. + +**How Source-NDO fits the three-layer model:** + +- **Layer 0** (`NondominiumIdentity`): Source-NDOs use `PropertyRegime::Nondominium` or `CommonPool` and `ResourceNature::Physical` or `Information`. The Layer 0 hash is the stable anchor for the source's event ledger. A linked `SourceProfile` extension entry carries condition indicators: `current_stock`, `flux_rate`, `assimilation_capacity`, `regime_state`, `resilience`, `tipping_threshold`, `stewarded_by` (replaces `primaryAccountable`). +- **Layer 1** (`SourceSpecification`): Boundary conditions, monitoring framework, ecological value vector, stakeholder map. Activated when governance framework formalisation begins. +- **Layer 2**: All boundary events (extraction, loading, non-consumptive use, regeneration) recorded as `EconomicEvent` entries against the Source Layer 0 hash. The governance-as-operator loop is cybernetic: events accumulate → stewards interpret conditions → `GovernanceRule` entries are revised → access affordances change → future events are conditioned. + +**ValueFlows extension required:** `vf:Source` as a typed flow endpoint role, distinct from `vf:Agent` and `vf:EconomicResource`, allowing `provider` and `receiver` fields in `EconomicEvent` to reference Source-NDOs directly. This is the single extension needed; all other ValueFlows semantics apply unchanged. See [`valueflows-1.0-compliance.md`](../hREA/valueflows-1.0-compliance.md) for the compliance note. + +**Key architectural invariants:** +- Source-NDOs use the same governance-as-operator pattern. The difference is that governance rules must be *adaptable* (Source condition changes trigger rule revision) rather than fixed at creation. This extends the governance zome with an adaptive governance loop. +- `PropertyRegime::Nondominium` and `CommonPool` are the only valid regimes; governance SHALL reject GovernanceRule entries that attempt to assert ownership of a Source-NDO. +- No `primaryAccountable` — the `stewardedBy: Vec` relation carries obligations (monitoring, ledger maintenance, governance rule revision), not property rights. +- Source-to-Source links (`yields`, `conditions`, `providedBy`) are native DHT link types, enabling representation of source hierarchies (watershed → river) and ecological coupling (forest conditions river flow). + +**COP alignment:** Source-NDO is a direct application of the black-box principle (Ashby 1956; Snowden & Boone 2007): complex ecological systems cannot be fully modelled; governance must be enacted on observable periphery (boundary events), not on claimed interior knowledge. The `complex_interior: true` flag on `SourceProfile` makes this epistemological stance machine-readable. + --- *This document is the normative NDO architecture reference. **Layer 0 is implemented in MVP** (`NondominiumIdentity`, lifecycle validation, discovery — PR #80). **Layers 1 and 2, the capability slot surface, operational-state split, and full governance-as-operator lifecycle** remain post-MVP targets documented here for incremental delivery. The legacy `ResourceSpecification` + `EconomicResource` + `GovernanceRule` model coexists until migration (Section 10) links retroactive anchors and activates layer links. Federation extensions (`NdoHardLink`, `Contribution`, `Agreement` — PR #103) are partial Layer 2 semantics in `zome_gouvernance`. See `documentation/IMPLEMENTATION_STATUS.md` for the live checklist.* diff --git a/documentation/requirements/post-mvp/Source-NDO.md b/documentation/requirements/post-mvp/Source-NDO.md new file mode 100644 index 0000000..25db9eb --- /dev/null +++ b/documentation/requirements/post-mvp/Source-NDO.md @@ -0,0 +1,1077 @@ +# PLANNING THE PAPER + +We are going to lay out 3 interlocking structures: + +* Thematic structure (what are we talking about) +* Pragmatic structure (why are we talking about this and that, and in this order) +* Logical and emotional structure (what is the argument, how do we deploy it and what emotions do we want to instill to the reader.) + +We are going to overlay these structures together below. For every bullet point, we are going to separate the structural components using the “|” character, composed as: thematic element | pragmatic element | logical and/or emotional element. + +Text in square brackets “\[...\]” are more granular instructions for you, the AI agent that works on the text. + +The final text will be built from this 3 layer structure. The thematic structure will appear more explicitly in the text, as sections or paragraphs. The pragmatic and logical/emotional structures will remain mostly implicit, shaping order, emphasis, transitions, and tone. + +Thesis to keep visible while writing: + +* Existing economic information systems make nature visible mainly as owned resource, natural capital, ecosystem service, externality, or legal person. These categories are insufficient for complex ecological systems. We propose `Source` / Source-NDO as a new economic-information primitive: a generative, non-ownable, partially unknowable system whose boundary events can be recorded, whose condition can be sensed, and whose access rules can adapt through stewardship governance. | give the writer a stable compass for the whole paper | make the paper feel like a focused contribution rather than a broad critique of economics + +The structures: + +* Introduction: externalities as economic information failure | open with the concrete problem shared by environmental practitioners, economists, policy actors, and activists | create urgency without starting from ideology + * Present ecological degradation linked to human economic activity: extraction, pollution, biodiversity loss, water stress, soil depletion, climate impacts, and ecosystem fragmentation. Keep this empirical, measurable, and scientifically grounded. \[Literature anchors: Millennium Ecosystem Assessment; IPBES global and values assessments; SEEA EA.\] | establish that the problem exists before proposing an ontology | build trust and realism + * Explain that an externality is not only a moral or pricing problem; it is also an information-system problem, because the effects of economic events often remain outside the economic record. \[Literature anchors: Pigou on divergence between private and social net product; Coase on social cost, rights, and transaction costs.\] | shift the reader from "environmental problem" to "economic information problem" | prepare the reader to accept an infrastructural/ontological proposal + * State the paper's practical goal: make ecological effects visible inside economic information systems so economic agents can steward natural sources/resources rather than merely consume resources. | clarify what the paper is trying to accomplish | orient the reader toward constructive action + +* Why existing economic categories fail | review familiar approaches without getting trapped in ideological debate | show that the proposed primitive responds to a gap shared across multiple paradigms + * Market accounting and conventional economics: nature appears as input, asset, cost, externality, or natural capital. \[Literature anchors: Pigou; Coase; Costanza et al.; Daly; Georgescu-Roegen.\] | summarize the dominant economic framing | show why ecological effects are often displaced outside transactions + * State planning, regulation, and policy frameworks: nature appears as managed stock, protected zone, compliance object, or public asset. \[Literature anchors: Scott's critique of state legibility and high modernism; SEEA as constructive statistical counterpoint.\] | acknowledge the state/regulatory path without making the paper a capitalism/socialism polemic | show that visibility and stewardship problems persist even when markets are constrained + * Ecosystem services and natural capital accounting, including SEEA: nature becomes legible through extent, condition, services, degradation, enhancement, and sometimes monetary valuation. \[Literature anchors: Daily; Costanza et al.; TEEB; SEEA EA; ARIES for SEEA.\] | connect to the strongest existing environmental accounting work | show respect for existing frameworks while preparing the distinction between description and governance + * Rights of Nature and ecological personhood: nature becomes legally represented as a rights-bearing person or subject. \[Literature anchors: Ecuador Constitution Articles 71-74; Te Awa Tupua Act 2017; Atrato River case if added later.\] | acknowledge an important activist/legal tradition | prepare the later argument that personification protects nature politically but creates ontological and governance problems + * Commons governance and Ostrom's resource systems: communities can steward shared resource systems through monitoring, sanctions, nested institutions, and adaptive rules. \[Literature anchors: Ostrom 1990, 2005, 2009; Folke et al. 2005.\] | introduce the strongest governance precedent | show that the paper builds on commons governance rather than replacing it + * REA and ValueFlows: economic events, agents, commitments, claims, and resources can be modeled with much more precision than conventional accounting allows. \[Literature anchors: McCarthy 1982; Geerts and McCarthy; ValueFlows specification.\] | introduce the information-system tradition that makes implementation plausible | prepare the reader for the worked modeling comparison + * Synthesis of the insufficiency: these approaches see parts of the problem, but none gives economic information systems a first-class object for a generative, unowned, complex ecological system that can accumulate event history and condition future access. | define the gap | create the opening for `Source` + +* The ontological gap: Agent, Resource, Source | introduce the conceptual core early | give the reader the simplest possible vocabulary for the rest of the paper + * Define `Agent`: an entity that can act, intend, commit, deliberate, bear responsibility, and participate in governance. Include individuals, organizations, networks, and possibly delegated artificial agents. | establish what agency means | prevent the later confusion between ecological causality and intention + * Define `Resource`: an appropriable or inventoriable output used in economic processes, such as water, timber, fish, energy, data, or a tool. | retain the usefulness of existing economic primitives | show that the paper is not rejecting resource accounting where it is appropriate + * Define `Source`: a generative system that yields resources, absorbs effects, conditions future possibilities, regenerates or degrades, and cannot honestly be reduced to either an owned resource or an intentional agent. | introduce the new primitive | make the central conceptual move clear + * Explain why nature-as-resource fails: the river, watershed, forest, wetland, or atmosphere is reduced to inventory, stock, asset, or service flow, which hides generative complexity and tends toward extraction. | clarify one category error | create dissatisfaction with reduction to resource + * Explain why nature-as-agent also fails: ecological systems do not form intentions, make commitments, deliberate, or bear responsibility; human representatives inevitably speak for them. Use the corporation-as-person analogy carefully and concisely. | clarify the second category error | protect the paper from anthropomorphic confusion while respecting Rights of Nature motivations + * Present `Source` as the third category: neither resource nor person, neither property nor agent, but a generative ecological/economic primitive around which stewardship can be organized. | stabilize the new ontology | give the reader a memorable conceptual anchor + +* Nature and economy as complex systems: the black-box principle | introduce the epistemology required by the proposal | move the reader from control/planning to stewardship/adaptation + * Explain that watersheds, forests, rivers, fisheries, soils, and atmospheres are complex systems: partially knowable, nonlinear, multi-scalar, path-dependent, and capable of regime shifts. \[Literature anchors: Holling 1973; Gunderson and Holling 2002; Folke et al. 2005.\] | establish the complexity requirement | show why complete representation is impossible + * Explain that the economy is also a complex adaptive system, not a clockwork machine that can be fully planned or optimized. | align ecological complexity with economic complexity | prepare the case for iterative governance loops + * Introduce the black-box principle: we do not model the full interior of the ecological system; we record boundary events, sense condition, and adapt governance. \[Literature anchors: Ashby's black box and requisite variety; Scott's critique of schematic simplification.\] | define the epistemic stance | replace false certainty with disciplined humility + * Connect this to Cynefin / probe-sense-respond, resilience theory, Panarchy, Morin, and adaptive governance. \[Literature anchors: Snowden and Boone 2007; Holling 1973; Gunderson and Holling 2002; Folke et al. 2005. ToDo: select the most appropriate references; avoid overloading the main text with theory.\] | ground the complexity argument in literature | make the proposal academically credible + +* Existing frameworks and what they miss | position the contribution in the literature | show continuity with prior work while making the novelty precise + * Ostrom and commons governance distinguish resource systems from resource units, which strongly resembles Source vs Resource. \[Literature anchors: Ostrom 1990; Ostrom 2009.\] | show that the idea has a commons-governance lineage | reassure readers that the proposal is not invented in isolation + * Social-Ecological Systems theory distinguishes resource systems, resource units, governance systems, and actors, but remains mostly analytical rather than executable. \[Literature anchors: Ostrom 2009; McGinnis and Ostrom if added later.\] | connect to SES literature | show the movement from description to implementation + * SEEA and ecosystem accounting make ecological condition and services visible, but do not by themselves condition future access through object-attached governance. \[Literature anchors: SEEA EA; ARIES for SEEA.\] | identify the "map vs cybernetic control system" distinction | make the implementation gap clear + * Ecological economics and natural capital recognize ecological limits and services, but often remain attached to stocks, flows, valuation, and capital metaphors. \[Literature anchors: Georgescu-Roegen; Daly; Daily; Costanza et al.; TEEB; IPBES Values Assessment.\] | acknowledge ecological economics as ally and limit case | prepare the ecological value vector as non-reductive alternative + * REA / ValueFlows model economic events well, but lack a first-class place for unowned generative sources that can be both flow origin and flow sink. \[Literature anchors: McCarthy; Geerts and McCarthy; ValueFlows spec.\] | identify the precise ontology gap in the chosen technical substrate | prepare the modeling demonstration + +* Worked case: modeling a river/watershed | turn the abstract argument into a concrete demonstration | help non-technical readers see the problem and solution in one memorable example + * Present the river/watershed case with multiple economic agents: agriculture, city utility, mining, hydro dam, fishing, tourism, forestry, and regeneration work. | make the problem empirical and relational | invite readers from policy/environment/economics into a shared case + * Model A: use ValueFlows 1.0 as-is. Show what it does well: economic events and derived resources such as gallons of water, fish, timber, and services. | avoid caricaturing ValueFlows | build fairness and credibility + * Show where Model A breaks: false ownership claim, resource-from-nowhere through `raise`, resource/agent contradiction for pollution, missing source hierarchy, missing source coupling, missing black-box construct, missing governance reflexivity. | expose the need for the new primitive | create a clear "before" picture + * Model B: augment ValueFlows with `vf:Source`. Show extraction, pollution, non-consumptive use, regeneration, and cross-source coupling as first-class economic events. | demonstrate the proposed primitive | create the "after" picture + * Use Occam's razor after the demonstration: adding one primitive removes multiple fictions and inexpressible residues. | justify the ontology surgically | convince the reader that this is a minimal, not bloated, extension + +* From visibility to stewardship: the governance loop | show why recording externalities is not enough | move from information to agency and institutional change + * Explain the loop: events -> ledger -> ecological interpretation -> policy/rules -> access affordances -> future events. | present the mechanism | show how the model becomes operational + * Show how extraction becomes visible: water abstraction, fish harvest, timber removal, biomass removal, soil removal. | make the ledger concrete | help readers imagine implementation + * Show how pollution/loading becomes visible: effluent, nutrient runoff, heavy metals, carbon emissions, sedimentation, heat, noise, or other relevant stressors. | make externalities first-class | create the core payoff of the paper + * Show how regeneration becomes visible: reforestation, riparian restoration, wetland repair, remediation, habitat restoration, pollution reduction, biodiversity enhancement. | avoid a purely punitive environmental ledger | create a regenerative and hopeful emotional direction + * Show how governance can condition future access: quotas, buffers, role requirements, monitoring requirements, restoration obligations, temporary restrictions, or graduated sanctions. | translate visibility into stewardship | make the model useful for policy and activism + * Explain why the model extends Ostrom into complex systems: rules are not designed once from complete knowledge; they adapt as the source ledger grows. | connect commons governance to complexity epistemology | make the originality claim stronger + +* Ecological value without reducing nature to price | articulate a value theory compatible with OVN, ecological economics, and complexity | prevent the model from being mistaken for another monetization framework + * Explain that in OVN terms value is relational: it arises from the relation between agents and what affects their goals, needs, viability, or capacity to act. | preserve the OVN value theory | avoid claiming that value lives inside nature as a thing + * Define ecological value as the contribution of an ecological Source to the maintenance, regeneration, resilience, adaptive capacity, and flourishing of socio-ecological systems. \[Literature anchors: IPBES Values Assessment; Costanza 2000/2020 on efficiency, fairness, sustainability; Folke et al. on adaptive capacity.\] | give the paper a usable definition | connect ecological value to stewardship rather than price + * Present the ecological value vector: Sustenance, Regeneration, Resilience, Adaptive Capacity, Generative Capacity, Commons Value, and Learning Value. \[Literature anchors: ecosystem services literature for sustenance; resilience/Panarchy for resilience/adaptation; commons/infrastructure literature for commons value; adaptive governance and knowledge commons for learning value.\] | make ecological value multidimensional and operationalizable | resist collapsing ecological value into one metric + * Connect the value vector to Source-NDO state: stock, flux, assimilation capacity, resilience, regime state, adaptive capacity, generative capacity, dependency index, and knowledge value. | show how value can be computed or interpreted from source state | bridge philosophy and information systems + +* Implementation: Nondominium hApp and Source-NDO | move from ontology to executable infrastructure | show that the proposal is not only theoretical + * Introduce Nondominium in the context of OVN, REA, ValueFlows, Holochain, and agent-centric infrastructure. Keep this concise for non-technical readers. | situate the implementation | make the technical stack legible without overwhelming the audience + * Explain the NDO as a governance-bearing object with identity, event history, attached rules, and stewardship relations, not as an owned asset. | connect Source to Nondominium architecture | show the property-regime innovation + * Explain how Source-NDO can make externalities visible: ecological Sources become endpoints for economic events, so extraction, loading, regeneration, and condition changes are no longer outside the ledger. | state the implementation payoff | reinforce the central thesis + * Explain the fivefold synthesis: commons governance (Ostrom), complexity epistemology (Morin/Cynefin/resilience), economic accounting (REA/ValueFlows), explicit externality tracking, and nondominium property relations. | consolidate the originality | leave the reader with a coherent synthesis + +* Limits, risks, and open questions | strengthen credibility and avoid techno-solutionism | show the proposal is responsible, situated, and open to governance + * Measurement quality: who produces ecological data, how sensors are trusted, how uncertainty is represented, and how missing data affects governance. | anticipate practical objections | build trust with scientific and policy readers + * Governance legitimacy: who interprets the ledger, who changes rules, who represents affected communities, and how conflicts are resolved. | address political reality | avoid the impression that information alone solves governance + * Indigenous, local, and experiential knowledge: how qualitative and place-based knowledge can inform the source ledger without being extracted or flattened. | widen the epistemic base | respect environmental justice and local stewardship traditions + * Data sovereignty and privacy: how communities control sensitive ecological and social data. | address risks of surveillance or enclosure | align the model with commons values + * Risk of green accounting capture: how to prevent Source-NDOs from becoming another way to legitimize extraction through better measurement. | name the adversarial failure mode | show moral seriousness + * Legal interoperability: how Source-NDO governance relates to rights of nature, public law, commons agreements, permits, and institutional policy. | connect the proposal to existing institutions | make adoption plausible + +* Conclusion: Source as missing primitive for ecological-economic information systems | close the argument | leave the reader with the paper's contribution in one sentence + * Restate the problem: externalities remain invisible when economic systems have no honest object for generative ecological systems. | return to the opening | create closure + * Restate the proposal: `Source` / Source-NDO is a third primitive alongside Agent and Resource. | make the core idea memorable | give readers a portable concept + * Restate the practical effect: extraction, pollution, regeneration, and ecological condition can become visible economic events around a stewarded, non-ownable, complex source. | summarize the utility | leave the reader with a constructive path + * End with the paradigm shift: the central economic question becomes not only "how much value was extracted?" but "how much generative capacity was maintained, enhanced, or degraded?" | close with a strong normative and emotional frame | move the reader from extraction to stewardship + +# MODELING + +## Modeling a river: ValueFlows 1.0 vs Augmented ValueFlows (vf:Source / Nondominium) + +A worked case study. + +We model a river as *commons* or *nondominium* in two ways, using plain ValueFlows 1.0 and ValueFlows augmented with a vf:Source. We use these two alternatives to specify a primitive in the Nondominium hApp called Nondominium Object (NDO). Then we use Occam’s razor to choose between these two representations. + +## 1\. The case + +A watershed feeds a river. The river spans a conflicting economic ecosystem: + +| Agent | Interaction with the river | Externality / conflict | +| :---- | :---- | :---- | +| **AgriCoop** (irrigation) | consumes water | nutrient runoff (N, P) pollutes downstream | +| **CityUtility** (public supply) | consumes water | needs clean water; harmed by upstream pollution | +| **MiningCo** | consumes water, discharges effluent | heavy metals pollute; conflicts with consumption and agriculture | +| **HydroDam** | uses flow (non-consumptive) | diverts and re-times flow, starving agriculture downstream | +| **FisherGuild** | extracts fish | overfishing degrades the biological regime, then water quality | +| **RiverTours** | uses the river for transport/recreation | low impact; harmed by pollution and low flow | +| **ForestryOp** | cuts trees in the watershed forest | deforestation degrades infiltration, then river flow and quality | +| **RegenCollective** | reforestation, riparian restoration, remediation | raises the generative capacity of the coupled sources | + +The goal: use **Nondominium** to align these agents toward sustainable use, arriving at what Ostrom would call successful commons stewardship, and going *beyond* Ostrom because the *resource system* is genuinely complex (the watershed), not merely complicated. + +### The governance loop (the mechanism) + +The watershed is a complex system that cannot be fully described, quantified, or managed. The model does **not** try to represent that complexity. It treats the watershed as a **black box** and captures only what is measurable at the boundary as ValueFlows *economic events*: trees cut, fish caught, gallons abstracted, kilograms of pollutant discharged, trees replanted. The river is an **NDO**: the *events* are logged against it, the ledger is handed to complexity scientists, academics, environmental orgs, and resource managers, who formulate policy, which is formalized into the NDO’s *governance rules*, which govern access for each agent, and which evolve as the ledger grows. The loop is: **observe boundary events, sense regime, adapt *governance*, condition future access.** That is Cynefin *probe-sense-respond* applied to a commons. + +## 2\. The source hierarchy and the black-box principle + +A watershed is a *source* of *sources*. The river cannot be separated from it: the river is as much a part of the whatershed as the bacteria, plants, animals, rock chemistry, and the atmospheric coupling (clouds, rain) that compose it. The watershed provides sub-sources (river, forest, fauna, flora), and those provide inventoriable economic resources. + + WATERSHED (complex system, black box) + / | \\ \\ + RIVER FOREST FAUNA FLORA (sub-sources) + | | | | + water m3 planks fish herbs (economic resources, inventoriable) + +Two distinct generative relations live here: + +* **Source provides Source** (watershed \-\> river): generative parenthood. +* **Source yields Resource** (river \-\> gallons of water): the inventoriable output ValueFlows already models well. + +The black-box principle: we never claim to model the interior of the watershed. We model the boundary flows (the *events*) and we govern the boundary (*access rules*). Everything below depends on this stance, and it is exactly where the two models diverge, because one of them has a place to put a black-boxed *generative commons* and the other does not. + +## 3\. Model A: ValueFlows 1.0 as is + +VF 1.0 offers EconomicResource, EconomicEvent, Agent (Person / Organization / EcologicalAgent), Process, Action, ResourceSpecification, plus the planning and exchange layers (Intent, Commitment, Agreement, Plan). The *events* ValueFlows models superbly. The trouble is everything the events are *about*. + +### What VF 1.0 does well: the *events* and the derived *resources* + +The gallons, fish, and planks, once appropriated, are proper EconomicResources, and the measurable acts are proper EconomicEvents. This part is correct and should be kept verbatim in both models. + +### Where it breaks: the river has no honest type + +To log “AgriCoop abstracted 10,000 m3 from the river,” VF 1.0 needs the water to come from somewhere. The river is the source, but VF 1.0 has only two slots for it, and both are fictions: + +**Fiction 1, the river as EconomicResource.** A *resource* requires primaryAccountable, defined as the *agent* with “primary rights and responsibilities (ownership).” Nondominium means *no dominium*, no owner. You must either invent an owner (a steward org as primaryAccountable), which **records a false ownership claim in the very ledger meant to be authoritative and destroys the nondominium regime**, or leave it null, which violates the *resource* model and breaks hREA implementations that require it. + +**Fiction 2, appropriation as raise.** If you refuse the owner, the only way to get water into AgriCoop’s inventory is raise (“adjust up to account for newly found resource without a process”). But raise has no provider and no source: the water appears from nowhere, and **the river’s depletion becomes invisible**. This is the phlogiston negative-mass move in concrete form: to keep the books balanced you posit resource from nothing. + +\# VF 1.0 abstraction event, option (a): depletion vanishes + +*EconomicEvent { action: raise, resourceInventoriedAs: Water\#agri, resourceQuantity: 10000 m3 }* +*\# provider: none.* + +The river is never debited. Sustainability is unaccountable. + +\# option (b): reintroduce the owner fiction + +*EconomicResource River { primaryAccountable: StewardOrg }* + +\# nondominium broken + +EconomicEvent { action: transfer, provider: StewardOrg, receiver: AgriCoop, quantity: 10000 m3 } + +**Fiction 3, the Resource/Agent contradiction.** Pollution is an output flow whose receiver must be an Agent. If the river is a *resource*, it cannot receive MiningCo’s effluent. To absorb pollution you must *also* type the river as an EcologicalAgent. Now the river is a *resource* (to inventory water) and an *agent* (to receive waste): one thing, two incompatible types, and the *agent* typing re-attributes the agency the prior synthesis showed it does not have. + +EconomicEvent { action: produce, provider: MiningCo, receiver: ???, resourceInventoriedAs: HeavyMetals } + +\# receiver must be an Agent. River-as-Resource cannot receive \-\> forced dual typing. + +### The residues VF 1.0 cannot express at all + +* **No Source-provides-Source edge**: the *watershed \-\> river* hierarchy is faked with containedIn (wrong: containment is not generation) or pushed to free text. +* **No cross-source coupling**: forest sustainability conditioning river flow and quality (the heart of the case) has no edge; it lives only in external analysis. +* **No black-box construct**: VF 1.0 assumes *resources* and *events* are fully specified. The epistemic stance “this interior is opaque and must not be modeled” is inexpressible. +* **No governance reflexivity**: the *events \-\> policy \-\> rules \-\> access* loop cannot close on the object. You can write Agreements and Commitments, but nothing anchors them to a governed commons that accumulates its own ledger and conditions its own future access. + +### Tally for Model A + +Three active fictions (false ownership, raise-from-nowhere, *resource/agent* contradiction) plus four inexpressible residues (hierarchy, coupling, *black box*, governance reflexivity). The “parsimonious” ontology produces a baroque, internally contradictory model that loses the very things the project exists to do: hold a commons in nondominium and steward a complex system. + +## 4\. Model B: Augmented ValueFlows with vf:Source + +Add one primitive: vf:Source. It is the ontology-layer type of what the property regime calls a Nondominium Object. They are the same entity from two angles: + +| vf:Source (ontology) | Nondominium Object (property regime) | +| :---- | :---- | +| unowned, no primaryAccountable | held in nondominium, no dominium | +| stewardedBy \-\> Agent | governance module and stewards | +| event ledger with the Source as flow endpoint | events logged against the NDO | +| conditions / affords edge | access capabilities granted by governance | +| opaque complexInterior, sensed via regimeState / resilience | “we do not model the watershed, we govern the boundary” | +| Source-to-Source coupling | *watershed \-\> river \-\> forest* sustainability links | + +The single new ontological affordance that does all the work: **flows may originate from and terminate in sources, not only *agents*.** + +### Entity inventory + +Source Watershed { complexInterior: true, stewardedBy: WatershedGovernance, provides: \[River, Forest, Fauna, Flora\] } +Source River { + providedBy: Watershed, + yields: \[WaterSpec, FishSpec\], + currentStock, fluxRate, assimilationCapacity, regimeState, resilience, tippingThreshold, + stewardedBy: RiverGovernance, \# no primaryAccountable: this is the point + realizedAs: NDO\#river \# the Nondominium Object +} +Source Forest { providedBy: Watershed, yields: \[TimberSpec\], conditions: River } + +### Key events, modeled cleanly + +\# Abstraction: the river is the provider (Source as flow origin); depletion is visible +EconomicEvent { action: extract, provider: River(Source), receiver: AgriCoop, quantity: 10000 m3 } + \-\> decrements River.currentStock + +\# Non-consumptive use: HydroDam uses the flux, altering the regime, not the stock +EconomicEvent { action: use, provider: River(Source), receiver: HydroDam, effect: River.regimeState } + +\# Pollution: the river is the receiver (Source as sink); loading is visible +EconomicEvent { action: produce, provider: MiningCo, receiver: River(Source), quantity: 50 kg HeavyMetals } + \-\> debits River.assimilationCapacity + +\# Fishing: the fauna/river source yields fish; extraction debits the biological stock +EconomicEvent { action: extract, provider: River(Source), receiver: FisherGuild, quantity: 500 fish } + +\# Regeneration: raises a coupled source, which conditions the river +EconomicEvent { action: raise, target: Forest(Source), provider: RegenCollective, quantity: 1000 trees } + \-\> Forest.conditions(River): improved infiltration raises River.fluxRate and resilience + +Every *event* now has an honest subject. No false owner, no raise-from-nowhere, no dual typing. Depletion, pollution loading, and regeneration are all first-class and visible on the *Source*. + +### Governance reflexivity, native + +The river NDO accumulates its own ledger. Complexity scientists read it and emit policy, formalized as *access rules* expressed through the affords edge: + +Affordance { source: River, agent: MiningCo, action: produce(pollutant), maxQuantity: 10 kg/month, rule: R-2026-03 } +Affordance { source: River, agent: AgriCoop, action: extract(water), maxQuantity: 8000 m3/season, rule: R-2026-04 } + +The loop closes on the object: *events \-\> ledger \-\> policy \-\> affordances \-\> conditioned future events*. The *Source* is the anchor that both accumulates the events and carries the *governance* that conditions the next ones. + +### Sustainability as a computable cross-source relation + +Because *Sources* couple (Forest.conditions(River)), sustainability is not a slogan but a relation over the source web: for each *Source*, compare withdrawals (extract \+ consume) and loading (produce\-into) against regeneration (raise) and assimilationCapacity, propagated across couplings. Deforestation shows up as a drop in Forest stock that lowers River fluxRate and resilience, tightening the river’s sustainable abstraction budget. The model makes the forest-river link an accounting fact. + +### Beyond Ostrom + +Ostrom’s design principles (clear boundaries, monitoring, graduated sanctions, conflict resolution, nested governance) largely assume a **complicated** *resource system* whose state can be tracked and whose rules can be designed from understanding it. The watershed is **complex**: its interior is opaque, its responses nonlinear, its regime shifts abrupt. **The Source-NDO extends Ostrom into the complex domain**: you cannot design optimal rules from understanding the system, so you sense the boundary ledger and adapt governance continuously, holding precautionary buffers against tipping points you cannot predict. The *black box* is not a limitation worked around; it is the honest design center. That is the “beyond Ostrom” move, and Model B is built for it while Model A has no place to put it. + +## 5\. The Occam’s razor verdict + +The razor’s naive reading favors Model A: VF 1.0 adds zero classes, the augmentation adds one. But the razor’s real target (Popper, Quine) is the multiplication of *ad hoc hypotheses* and unexplained residue, not the size of the vocabulary. It operates on two levels: + +* **Ontological parsimony**: how many classes the vocabulary names. +* **Model parsimony**: how many entities and fictions a faithful representation must posit. + +Adding vf:Source raises the first and sharply lowers the second. + +| | Model A (VF 1.0) | Model B (augmented) | +| :---- | :---- | :---- | +| New classes | 0 | 1 (vf:Source \= NDO) | +| False ownership claim | required (Fiction 1\) | none (Source has no owner) | +| Resource from nowhere (raise) | required to hide depletion (Fiction 2\) | none (Source is debited) | +| Resource/Agent contradiction | required for pollution (Fiction 3\) | none (Source is sink) | +| Source hierarchy | inexpressible | native edge | +| Cross-source coupling | inexpressible | native edge | +| Black-box epistemics | inexpressible | native (complexInterior) | +| Governance reflexivity | out of band | native (ledger \-\> affordances) | + +The decisive argument: **Occam’s razor minimizes the entities a theory must posit, not the terms in its vocabulary.** Nondominium Objects already exist in this system; the project is built on them. VF 1.0, lacking a type for them, must reconstruct each NDO out of mismatched parts plus three fictions. That reconstruction *posits more* (a fake owner, a phantom raise, a contradictory dual type) than simply admitting the entity that is already there. Refusing to name the Source does not remove it from the world; it forces you to smuggle it in piecemeal and falsely. The augmented ontology is more parsimonious at the level that matters: the furniture of reality it commits you to. VF 1.0 here is “simpler than possible” (the Einstein corrective): the honest simplest theory that fits a complex, unowned, generative, governed commons needs the Source primitive. + +There is also an **epistemic razor**. Model A, by typing the river as a fully specified Resource, implicitly claims the watershed is analyzable (complicated). The case states it is not. Model B’s *black-box* Source matches the complex-domain epistemics and refuses to posit a describable interior it can never verify. Do not multiply *unverifiable* entities: another reason the razor cuts toward B. + +### Steelman of A, and rebuttal + +The strongest case for A: “Use EconomicResource with a convention (primaryAccountable \= a commons DAO, classifiedAs nondominium) and handle hierarchy, coupling, and governance in the hREA app layer. Ontologies need not model everything.” The rebuttal: pushing it to the app layer means the ontology stops being the shared semantic substrate, so every implementation reinvents nondominium and source semantics privately, defeating interoperability, the whole reason for a shared vocabulary. And the dominium fiction is not a neutral convention: primaryAccountable asserts ownership rights, the exact inverse of nondominium. Writing a false property claim into the authoritative ledger is a misstatement of the regime, not a shortcut. Parsimony and correctness point the same way. + +## 6\. Recommendation + +Choose the **augmented ValueFlows**, but augment surgically. The augmentation is minimal and located precisely at the joint where VF 1.0 forces fictions: + +* **Keep VF 1.0 unchanged** for the *event* ledger and the derived *resources* (gallons, fish, planks). It is correct there, in both models. +* **Add vf:Source** as the type of the Nondominium Object: the unowned, black-boxed, generative commons that anchors the ledger, absorbs pollution, yields resources, couples to other sources, and carries evolving governance. + +This is itself a razor-friendly result: the smallest possible addition (one primitive) removes the largest amount of fiction (three active fictions plus four inexpressible residues), and it names an entity the system already contains. The new entity pays for itself many times over in eliminated epicycles. + +## 7\. Coda: what this means for Nondominium + +vf:Source gives Nondominium its missing ontological foundation. An NDO is not a resource that happens to be unowned; it is a *Source*: a complex, generative, agentless commons whose interior is opaque and whose stewardship is the continuous, ledger-driven, complexity-informed adaptation of access rules at its boundary. Modeling it as a Source rather than a *resource* is what lets Nondominium be both faithful to the property regime (no dominium) and honest about the science (irreducible complexity), and it is what carries commons stewardship beyond Ostrom into the complex domain. + +# PERTINENT LITERATURE + +We are attempting to ground an ontology and accounting infrastructure that can: + +1. Represent ecosystems as *generative commons* rather than *owned resources*. +2. Capture externalities as first-class *economic events*. +3. Track extraction, regeneration, pollution, ecological condition, and source-to-source coupling. +4. Govern access through adaptive, polycentric, object-attached institutions. +5. Treat ecosystems as *complex systems* whose internal dynamics remain partially opaque. +6. Create information infrastructures that connect ecological observations, accounting systems, governance rules, and economic activity. +7. Move beyond static resource accounting toward reflexive governance: *events -> ledger -> interpretation -> policy/rules -> access affordances -> future events*. + +The literature should be organized around the claims we need to defend, not only around academic domains. + +## Claim-To-Literature Map + +| Claim we need to support | Primary sources | What they contribute | Source-NDO extension | +| ----- | ----- | ----- | ----- | +| Externalities are effects not captured by the private transaction | Pigou, *The Economics of Welfare* (1920/1932), Part II, Ch. IX; Coase, "The Problem of Social Cost" (1960) | Pigou frames divergence between private and social net product; Coase reframes externalities through reciprocal harm, rights, and transaction costs | Source-NDO turns the ecological endpoint into a ledger endpoint, making the "outside" of the transaction recordable | +| Commons can be governed without privatization or central command | Ostrom, *Governing the Commons* (1990); Ostrom, *Understanding Institutional Diversity* (2005); Ostrom, "A General Framework for Analyzing Sustainability of Social-Ecological Systems" (2009) | Monitoring, graduated sanctions, nested institutions, resource systems/resource units, governance systems, actors | Source-NDO makes the resource system an executable information object rather than only an analytical category | +| Ecological systems are complex, nonlinear, and regime-shifting | Holling, "Resilience and Stability of Ecological Systems" (1973); Gunderson & Holling, *Panarchy* (2002); Folke et al., "Adaptive Governance of Social-Ecological Systems" (2005) | Resilience, adaptive cycles, cross-scale dynamics, adaptive governance, transformation under disturbance | Source-NDO encodes complexity epistemology through boundary observation and adaptive rule evolution | +| Complete ecological representation is impossible or dangerous as a governance assumption | Ashby, *An Introduction to Cybernetics* (1956); Scott, *Seeing Like a State* (1998); Snowden & Boone, "A Leader's Framework for Decision Making" (2007) | Black-box theory, requisite variety, critique of schematic legibility, probe-sense-respond in complex contexts | Source-NDO refuses to model the full interior; it governs observable boundary events and source state signals | +| Ecosystem services and natural capital make nature economically visible but often through service/capital metaphors | Daily, *Nature's Services* (1997); Costanza et al., "The Value of the World's Ecosystem Services and Natural Capital" (1997); TEEB (2010); Millennium Ecosystem Assessment (2005) | Ecosystem services, natural capital, valuation, human dependence on ecosystem functions | Source-NDO keeps the visibility goal but avoids reducing sourcehood to price, asset, or service flow | +| Environmental-economic accounting already tracks ecosystem extent, condition, services, and assets | SEEA Central Framework (2012); SEEA Ecosystem Accounting (2021); ARIES for SEEA | International statistical standard; spatial ecosystem accounts; extent, condition, physical and monetary service accounts; automated data/model integration | Source-NDO adds a reflexive governance layer: accounts condition future access instead of remaining descriptive | +| Values of nature are plural and cannot be reduced to one monetary metric | IPBES Values Assessment (2022); Costanza, "Social Goals and the Valuation of Ecosystem Services" (2000); Costanza et al., "Valuing natural capital and ecosystem services toward the goals of efficiency, fairness, and sustainability" (2020) | Intrinsic, instrumental, relational values; efficiency, fairness, sustainability; valuation as goal-relative | Source-NDO ecological value vector can express sustenance, regeneration, resilience, adaptation, generation, commons, and learning | +| Economic information systems need explicit ontological primitives | McCarthy, "The REA Accounting Model" (1982); Geerts & McCarthy on REA ontology; ValueFlows specification | Resources, Events, Agents; commitments and claims; economic event ledgers | Source-NDO proposes one surgical primitive missing from REA/ValueFlows: a generative source that can be flow origin/sink without being owner or agent | +| Classifications and information infrastructures shape reality; they are not neutral | Star & Ruhleder, "Steps Toward an Ecology of Infrastructure" (1996); Bowker & Star, *Sorting Things Out* (1999) | Infrastructure is relational and embedded; classifications have moral and political consequences | Adding `Source` is not just vocabulary; it changes what economic systems can see, govern, and protect | +| Rights of Nature legally protects ecosystems but often through personhood | Ecuador Constitution (2008), Arts. 71-74; Te Awa Tupua Act (2017); Atrato River case (to verify if used) | Nature as rights-bearing subject or legal person; human guardians speak for the ecological entity | Source-NDO offers a non-personifying alternative: governance attached to a source without pretending the source has intentions | + +## Core Bibliography To Use First + +### Externalities, Social Cost, and Economic Blind Spots + +* Pigou, A. C. (1920/1932). *The Economics of Welfare*, especially Part II, Chapter IX, "Divergences between Marginal Social Net Product and Marginal Private Net Product." Use to ground the classical externality problem. +* Coase, R. H. (1960). "The Problem of Social Cost." *Journal of Law and Economics*, 3, 1-44. https://doi.org/10.1086/466560. Use as the institutional/property-rights counterpoint to Pigou. +* Georgescu-Roegen, N. (1971). *The Entropy Law and the Economic Process*. Harvard University Press. Use to ground the biophysical critique of treating the economy as a closed circular flow. +* Daly, H. E. (1977/1991). *Steady-State Economics*. W. H. Freeman / Island Press. Use to ground ecological limits, throughput, and the economy as subsystem of a finite biosphere. + +### Commons, SES, and Adaptive Governance + +* Ostrom, E. (1990). *Governing the Commons*. Cambridge University Press. Use for the design principles of commons governance. +* Ostrom, E. (2005). *Understanding Institutional Diversity*. Princeton University Press. Use for institutional analysis and rule diversity. +* Ostrom, E. (2009). "A General Framework for Analyzing Sustainability of Social-Ecological Systems." *Science*, 325(5939), 419-422. https://doi.org/10.1126/science.1172133. Use for Resource System / Resource Unit / Governance System / User categories. +* Folke, C., Hahn, T., Olsson, P., & Norberg, J. (2005). "Adaptive Governance of Social-Ecological Systems." *Annual Review of Environment and Resources*, 30, 441-473. https://doi.org/10.1146/annurev.energy.30.050504.144511. Use for adaptive governance, learning, bridging organizations, and crisis-as-transformation. +* Berkes, F. (2012). *Sacred Ecology* (3rd ed.). Routledge. Use for indigenous and traditional ecological knowledge, but be careful not to instrumentalize it. + +### Complexity, Resilience, Black-Box Epistemology + +* Holling, C. S. (1973). "Resilience and Stability of Ecological Systems." *Annual Review of Ecology and Systematics*, 4, 1-23. https://doi.org/10.1146/annurev.es.04.110173.000245. Use for ecological resilience and non-equilibrium thinking. +* Gunderson, L. H., & Holling, C. S. (Eds.). (2002). *Panarchy: Understanding Transformations in Human and Natural Systems*. Island Press. Use for cross-scale adaptive cycles. +* Ashby, W. R. (1956). *An Introduction to Cybernetics*. Chapman & Hall. Use for black-box theory and the Law of Requisite Variety. +* Snowden, D. J., & Boone, M. E. (2007). "A Leader's Framework for Decision Making." *Harvard Business Review*, 85(11), 68-76. Use for Cynefin and probe-sense-respond in complex contexts. +* Scott, J. C. (1998). *Seeing Like a State*. Yale University Press. Use as a warning against over-legibility and centralized simplification of complex natural/social systems. + +### Ecosystem Services, Natural Capital, and Plural Values + +* Daily, G. C. (Ed.). (1997). *Nature's Services: Societal Dependence on Natural Ecosystems*. Island Press. Use for ecosystem services and life-support framing. +* Costanza, R., d'Arge, R., de Groot, R., et al. (1997). "The Value of the World's Ecosystem Services and Natural Capital." *Nature*, 387, 253-260. https://doi.org/10.1038/387253a0. Use as the landmark valuation paper; treat it as important but not the final model. +* Millennium Ecosystem Assessment. (2005). *Ecosystems and Human Well-being: Synthesis*. Island Press / World Resources Institute. Use for provisioning, regulating, cultural, and supporting services. +* TEEB. (2010). *The Economics of Ecosystems and Biodiversity: Mainstreaming the Economics of Nature*. Use for policy-facing ecosystem valuation and biodiversity economics. +* IPBES. (2022). *Methodological Assessment Report on the Diverse Values and Valuation of Nature*. Use to support plural, relational, intrinsic, and instrumental values of nature. +* Costanza, R. (2000). "Social Goals and the Valuation of Ecosystem Services." *Ecosystems*, 3, 4-10. Use to support valuation relative to efficiency, fairness, and sustainability. +* Costanza, R., et al. (2020). "Valuing natural capital and ecosystem services toward the goals of efficiency, fairness, and sustainability." *Ecosystem Services*, 43, 101096. Use as updated plural-value ecological economics. + +### Environmental Accounting and Information Infrastructure + +* United Nations et al. (2012). *System of Environmental-Economic Accounting 2012: Central Framework*. Use for the official environmental-economic accounting baseline. +* United Nations et al. (2021). *System of Environmental-Economic Accounting--Ecosystem Accounting (SEEA EA)*. Use as the most important official framework for ecosystem extent, condition, services, degradation, and enhancement. +* ARIES for SEEA. Use as the closest existing implementation precedent: an open-source, semantically informed modeling platform for compiling ecosystem accounts according to SEEA EA. +* Star, S. L., & Ruhleder, K. (1996). "Steps Toward an Ecology of Infrastructure." *Information Systems Research*, 7(1), 111-134. https://doi.org/10.1287/isre.7.1.111. Use to frame Source-NDO as infrastructure, not just an ontology. +* Bowker, G. C., & Star, S. L. (1999). *Sorting Things Out: Classification and Its Consequences*. MIT Press. Use to justify why adding the `Source` category has practical and political consequences. + +### REA, ValueFlows, and Economic Ontologies + +* McCarthy, W. E. (1982). "The REA Accounting Model: A Generalized Framework for Accounting Systems in a Shared Data Environment." *The Accounting Review*, 57(3), 554-578. Use as the origin of Resource-Event-Agent accounting. +* Geerts, G. L., & McCarthy, W. E. (2002). "An ontological analysis of the economic primitives of the extended-REA enterprise information architecture." *International Journal of Accounting Information Systems*, 3(1), 1-16. Use for REA as economic ontology. +* ValueFlows specification. Use the official vocabulary to ground claims about `EconomicResource`, `EconomicEvent`, `Agent`, `ResourceSpecification`, `Commitment`, and `Claim`. + +### Rights of Nature, Legal Personhood, and Category Boundaries + +* Constitution of the Republic of Ecuador (2008), Articles 71-74. Use for national constitutional recognition of Rights of Nature / Pacha Mama, including rights to existence, regeneration, restoration, and non-appropriation of environmental services. +* Te Awa Tupua (Whanganui River Claims Settlement) Act 2017. Use for legal personhood: the Act declares Te Awa Tupua a legal person with rights, powers, duties, and liabilities, exercised by Te Pou Tupua. +* Atrato River judgment (Colombia, 2016). \[ToDo: verify official citation before relying on it.\] Use only if we want a broader Rights of Nature comparison. + +## High-Priority Sources For The Actual Paper + +If the paper must be concise, prioritize these: + +1. Pigou, *The Economics of Welfare*. +2. Coase, "The Problem of Social Cost." +3. Ostrom, *Governing the Commons*. +4. Ostrom, "A General Framework for Analyzing Sustainability of Social-Ecological Systems." +5. Holling, "Resilience and Stability of Ecological Systems." +6. Gunderson & Holling, *Panarchy*. +7. Folke et al., "Adaptive Governance of Social-Ecological Systems." +8. SEEA Ecosystem Accounting. +9. ARIES for SEEA. +10. McCarthy, "The REA Accounting Model." +11. ValueFlows specification. +12. IPBES Values Assessment. +13. Bowker & Star, *Sorting Things Out*. +14. Te Awa Tupua Act 2017 and Ecuador Constitution Articles 71-74. + +Together these support the paper's major claims: externalities as accounting failures, commons stewardship, social-ecological systems, complexity and black-box governance, ecosystem accounting, plural values of nature, information infrastructure, economic event ontologies, and the limits of ecological personhood. + +## Source Validation Notes + +* SEEA EA is an official UN statistical framework adopted by the UN Statistical Commission in March 2021. Its core accounts are extent, condition, physical ecosystem services, monetary ecosystem services, and monetary ecosystem assets. +* Ostrom's 2009 *Science* paper explicitly distinguishes four first-tier SES subsystems: resource systems, resource units, governance systems, and users. +* Holling's 1973 paper is in *Annual Review of Ecology and Systematics*, 4, 1-23, DOI 10.1146/annurev.es.04.110173.000245. +* Folke et al. 2005 is in *Annual Review of Environment and Resources*, 30, 441-473, DOI 10.1146/annurev.energy.30.050504.144511. +* McCarthy's REA paper appeared in *The Accounting Review*, 57(3), 554-578. +* Costanza et al. 1997 appeared in *Nature*, 387, 253-260, DOI 10.1038/387253a0. +* Te Awa Tupua Act 2017, section 14, declares Te Awa Tupua a legal person and specifies that rights, powers, duties, and liabilities are exercised through Te Pou Tupua. + +# PRIOR KNOWLEDGE + +What follows is not a legal novelty claim. It is an intellectual positioning exercise: where does Source-NDO sit relative to existing bodies of knowledge, and what exact gap does it fill? + +## 1. Situating The Source-NDO Within Existing Literature + +The Source-NDO sits at the intersection of several traditions that usually remain separate: + +| Tradition | Primary object of analysis | What it gives us | What remains missing | +| ----- | ----- | ----- | ----- | +| Welfare economics and externalities | Private/social costs and benefits | A reason ecological effects disappear from transactions | A ledger object that makes the ecological endpoint explicit | +| Commons studies | Institutions, rules, collective action | Stewardship without privatization or central command | Executable resource-system objects in accounting infrastructure | +| Social-ecological systems | Resource systems, units, actors, governance systems | A diagnostic ontology for coupled human/ecological systems | Machine-readable economic event participation by resource systems | +| Ecological economics | Biophysical limits, natural capital, ecosystem services | The economy as embedded in ecological life-support systems | A non-reductive primitive for generative sources beyond capital/services | +| Resilience and complexity science | Adaptive cycles, regime shifts, emergence | A reason complete ecological modeling is impossible | An information-system pattern for black-box stewardship | +| Environmental accounting | Extent, condition, services, assets | Statistical visibility for ecosystems | Reflexive governance that conditions future economic access | +| Information infrastructure studies | Standards, classifications, infrastructure | Awareness that categories shape action and power | A new category that makes externalities governable without enclosure | +| REA / ValueFlows | Economic resources, events, agents | Event-centric economic accounting | A source primitive that can originate/receive flows without being owner or agent | +| Rights of Nature | Legal subjects and ecological guardianship | Legal/political protection of ecological entities | A non-personifying way to attach governance to nature | + +The central observation is that none of these traditions by itself possesses a satisfactory operational category corresponding to what we call a **Source**: a generative, non-ownable, partially unknowable entity that yields resources, receives ecological effects, conditions future economic possibilities, and accumulates the historical evidence required for its own governance. + +## 2. Economics: Externality As Displaced Information + +Pigou gives us the classical formulation: private net product and social net product can diverge. This is the basis for understanding pollution, depletion, and ecological degradation as effects that do not return to the decision calculus of the actor producing them. + +Coase complicates this by showing that externalities are also institutional and relational: harms are reciprocal, rights matter, and transaction costs determine whether parties can bargain or must rely on institutional design. This is useful for Source-NDO because the proposal is not merely "tax the polluter" or "price the service." It asks a prior information-system question: *where does the ecological effect appear in the shared record?* + +Source-NDO reframes externality as a ledger topology problem. If the river cannot be a flow endpoint, pollution remains outside the economic event record or is routed through a fictional agent/resource. If the river is a Source, the event can be written as `MiningCo -> River(Source)`, and the externality becomes internal to the information system without pretending the river is a person or an owned asset. + +## 3. Ecological Economics: Nature As Capital, Services, And Biophysical Limit + +Georgescu-Roegen and Daly supply the biophysical foundation: the economy is not a closed circular flow of exchange value. It is an open subsystem of a finite, entropic biosphere. This supports the paper's critique of treating ecosystems as ordinary inventory. + +Daily, Costanza, the Millennium Ecosystem Assessment, TEEB, and SEEA make nature visible through services, natural capital, extent, condition, and ecosystem asset accounts. This is indispensable. The paper should not dismiss this tradition. It should say: this work made a major step by making nature legible to economics and policy. + +The Source-NDO departure is narrower and more precise. Ecosystem services frameworks usually describe what nature contributes to humans. Source-NDO describes the generative system as an economic-information endpoint. It can yield resources, absorb pollution, condition other sources, and carry governance rules. The Source is not merely the stock behind a service flow; it is the governed, event-bearing object around which stewardship occurs. + +IPBES and Costanza's later work on plural valuation help prevent a common misunderstanding: the proposal is not simply a new monetary valuation mechanism. Source-NDO is compatible with monetary valuation where communities choose it, but its deeper value contribution is multidimensional: sustenance, regeneration, resilience, adaptation, generation, commons dependence, and learning. + +## 4. Ostrom And SES: Resource Systems Become Executable Objects + +Ostrom's distinction between resource systems and resource units is the closest conceptual ancestor of Source vs Resource: + +| Ostrom / SES | Source-NDO | +| :---- | :---- | +| Resource system | Source | +| Resource unit | Resource | +| Governance system | Object-attached governance rules and institutions | +| Users / actors | Agents | +| Action situation | Economic events, commitments, claims, and governance transitions | + +Examples: + +| Resource system / Source | Resource unit / Resource | +| :---- | :---- | +| Forest | Timber, carbon sequestration, habitat functions | +| Fishery | Fish | +| Irrigation system / watershed | Water | +| Wetland | Flood buffering, water purification, biomass | + +The difference is operational. In Ostrom and SES theory, the resource system is an analytical category for researchers and practitioners. In Source-NDO, the Source is a machine-readable accounting and governance object: events can originate from it, terminate in it, be logged against it, and condition access rules attached to it. + +This is the paper's bridge from commons analysis to economic information infrastructure. + +## 5. Complexity, Resilience, And The Black-Box Principle + +Holling, Panarchy, and adaptive governance literature establish that ecosystems are not merely complicated systems awaiting better measurement. They are complex adaptive systems with nonlinear dynamics, cross-scale coupling, thresholds, resilience, and transformation. + +Ashby gives us a language for the black-box principle. A system may be too large, inaccessible, or complex to inspect internally. Governance does not require complete internal representation; it requires enough variety in observation and response to keep essential variables within viable bounds. + +Scott provides the warning: attempts to make nature and society legible for centralized administration often simplify away the local, practical, ecological relationships that matter. This supports a careful design constraint: Source-NDO should not become another high-modernist over-modeling apparatus. It must preserve uncertainty, local knowledge, plural interpretation, and adaptive revision. + +Cynefin gives a practical governance frame: in complex domains, the appropriate pattern is not predict-plan-control, but probe-sense-respond. The Source-NDO governance loop matches this: + +* observe boundary events, +* sense source condition and regime, +* interpret through science and situated knowledge, +* adapt governance rules, +* condition future access, +* learn from the next round of events. + +## 6. SEEA And ARIES: From Ecosystem Accounts To Reflexive Governance + +SEEA EA is the strongest existing benchmark for ecosystem accounting. It organizes spatially explicit accounts for ecosystem extent, condition, physical ecosystem service flows, monetary ecosystem service flows, and monetary ecosystem assets. ARIES for SEEA is especially relevant because it shows that semantically informed tools can automate and customize ecosystem account compilation across territories. + +The Source-NDO should be positioned as complementary, not competitive. SEEA answers: *How can ecosystem condition and services be statistically represented and linked to economic activity?* Source-NDO asks: *How can economic activity around an ecological source be recorded in a way that changes future permissions, responsibilities, and stewardship rules?* + +The difference is the reflexive loop: + +*SEEA-style account -> policy insight* + +versus + +*Source-NDO event ledger -> ecological interpretation -> governance rule -> conditioned future event* + +In short: SEEA is closest to the map; Source-NDO aspires to be part of the governance cybernetics. + +## 7. REA, ValueFlows, And The Missing Primitive + +McCarthy's REA model is foundational because it moves accounting away from account balances as primary objects and toward economic phenomena: Resources, Events, and Agents. ValueFlows extends this pattern into open, networked economic coordination with commitments, claims, processes, resource specifications, and event vocabularies. + +This is exactly the right substrate for the paper's purposes. The problem is not that REA/ValueFlows are wrong. The problem is that their primitive set forces ecological systems into categories that do not fit: + +* If a river is an `EconomicResource`, it tends to require an ownership or primary-accountable fiction. +* If a river is an `Agent`, it receives person-like agency it does not possess. +* If water appears through `raise`, depletion from the river/source can disappear from the ledger. + +The Source primitive is therefore not a wholesale replacement of ValueFlows. It is a minimal extension at the exact point where the ontology otherwise creates fictions. + +## 8. Rights Of Nature: Important Protection, Problematic Ontology + +Rights of Nature and ecological personhood should be treated with respect. Ecuador's Constitution and the Te Awa Tupua Act are serious legal and political innovations responding to real failures of property law and environmental regulation. + +The Source-NDO critique is not that these movements are wrong to protect nature. The critique is that legal personhood can introduce a category ambiguity: rivers, forests, and watersheds do not deliberate, commit, form intentions, or bear responsibility. Their rights and duties must be exercised through human representatives. This may be practical in law, but it is dangerous if imported directly into economic ontology. + +Source-NDO offers a third path: attach governance to ecological systems without personifying them. A Source can be protected, stewarded, monitored, and governed without being an Agent. + +## 9. Information Infrastructure: Why The Category Matters + +Bowker and Star are important because they show that classification systems do not merely describe reality. They organize work, allocate visibility, distribute power, and silence some relations while amplifying others. + +This means adding `Source` is not a cosmetic vocabulary change. It changes what the economic information system can see: + +* without Source, depletion can become invisible, +* without Source, pollution has no honest receiver, +* without Source, cross-source coupling remains external analysis, +* without Source, governance cannot attach directly to the ecological object, +* without Source, externalities remain structurally external. + +From an information-infrastructure perspective, Source-NDO is a classification intervention with practical consequences. + +## 10. Where The Source-NDO Appears Most Original + +The strongest originality emerges where several traditions fail to connect. + +### A. Ontological Separation Of Source And Resource + +Many frameworks distinguish resource systems and resource units analytically. Few make that distinction operational inside economic event infrastructure. Source-NDO makes the distinction machine-readable and action-relevant. + +### B. Nondominium As An Ontological And Institutional Primitive + +Most institutional frameworks assume private, public, collective, or common property. Source-NDO introduces governable-without-ownership as an economic-information category. Stewardship becomes separable from dominium. + +### C. Integration Of Externalities Into The Ledger + +Externalities are no longer merely outside effects to price later. They become event flows with ecological endpoints. Pollution, extraction, and regeneration become part of the record around the Source. + +### D. Governance Attached To Ecological Objects + +Most governance systems revolve around organizations. Source-NDO shifts the center of gravity toward the ecological object itself: watershed, river, forest, fishery, wetland, atmosphere. Governance becomes attached to the source being affected. + +### E. From Representation To Execution + +Most literature discussed above is descriptive, analytical, legal, or statistical. Source-NDO asks whether a generative ecological system can become an executable governance primitive in an economic information system. + +## A Deeper Interpretation + +Looking across the literature, the Source-NDO is best understood not merely as environmental accounting and not merely as commons governance. It is a proposed new category of economic object: + +*a generative, stewarded, non-ownable, partially unknowable entity that conditions the production of economic resources and accumulates the historical evidence required for its own governance.* + +Pieces of this appear in: + +* Pigou and Coase: externalities, rights, and social cost, +* Ostrom: commons institutions and resource systems, +* SES theory: coupled resource/governance/user systems, +* Holling and Panarchy: resilience, adaptive cycles, and regime shifts, +* Ashby and Cynefin: black-box observation and probe-sense-respond, +* SEEA and ARIES: ecosystem accounts and environmental data infrastructure, +* IPBES and ecological economics: plural values and natural capital critique, +* REA/ValueFlows: event-centric accounting, +* Bowker and Star: the politics of classification and infrastructure, +* Rights of Nature: legal recognition of ecological entities. + +The paper's contribution is the synthesis: turning those fragments into a single operational primitive for ecological-economic information systems. + +# COMPLEXITY ECONOMICS + +We think that here is a deeper interpretation that goes beyond environmental accounting. The Source-NDO may represent an attempt to solve what I would call the **missing ontological layer of complexity economics**. + +## **1\. The hidden weakness in most complexity economics** + +Most complexity economists agree on several propositions: + +* economies are complex adaptive systems, +* emergence matters, +* agents are heterogeneous, +* networks matter, +* equilibrium is generally absent, +* adaptation and learning are fundamental. + +However, most complexity economics still focuses primarily on: agents, interactions, networks and institutions. The ontology remains largely anthropocentric. Even in the Santa Fe tradition, the economy is usually modeled as a population of interacting adaptive agents. The environment appears mostly as constraints, resources or exogenous conditions. This creates a paradox: complexity economics claims that economies are embedded in larger complex systems, but its models often stop at the boundary of human actors. + +## **2\. P2P economics extends complexity economics** + +This is widely covered in recent Sensorica writings, which argue that P2P systems are not merely compatible with complexity economics; they may constitute an organizational response to rising societal complexity. Hierarchical institutions fail because complexity exceeds centralized processing capacity, while distributed peer networks process information through self-organization and feedback. This is already an extension of complexity economics. + +Complexity economics explains *why economies behave as complex adaptive systems*. P2P theory asks what organizational forms are capable of operating effectively within such systems? + +The Source-NDO primitive adds another layer. As neoclassical economics focused on the *market actor*, complexity economics recognizes expands to the adaptive agent, which becomes a networked peer in P2P economics. They all treat resources pretty much the same way, as accountable, inputs and outputs of economic processes. Neither speak about a *generative resource*. The shift is subtle but profound. The Source-NDO says: *the economy is not only composed of agents interacting.* It is composed of agents, networks, institutions, economic resources, as well as generative sources. The watershed itself becomes part of the economic ontology, not as a resource, not as a stakeholder, not as a legal person, but as a generative system. + +## **4\. Introducing generative causality** + +Complexity economics usually models: ***Agent → Agent interactions*** or ***Agent → Network interactions***. The Source-NDO introduces: ***Source → Source interactions***. Examples: + +* Forest → River +* River → Fish population +* Wetland → Watershed + +So the economic system becomes embedded in a network of generative systems. This is much closer to ecological reality. In fact, one could argue that the Source-NDO introduces a form of **ecological causality** that complexity economics generally lacks. The economy is no longer a self-contained adaptive system, it becomes a subsystem of a larger adaptive system. + +## **5\. The deepest connection with Morin** + +This is where we see a very strong alignment with Edgar Morin. Morin repeatedly criticizes what he calls reductionism: + +* separating object from context, +* separating part from whole, +* separating system from environment. + +The Source-NDO does something unusual, it creates an accounting object that is simultaneously inside the economy and outside the economy. The watershed is not reducible to economic activity. Yet economic activity cannot be understood without it. This is very close to Morin's principle of recursive organization: *the product becomes a producer of what produces it*. The watershed produces economic activity. Economic activity alters the watershed. The modified watershed alters future economic activity. This recursive loop is largely absent from conventional accounting. + +## **6\. The most important thing still missing** + +We think that there is one major complexity-economic concept that is not yet fully present in the model. We talk about stocks, withdrawals, regeneration, pollution, resilience and tipping points. But we don’t fully represent **emergence**. Complexity economics is fundamentally concerned with emergent structures. The Source-NDO currently captures: state, condition, events. But not emergence itself. + +### **Example** + +A watershed does not merely regenerate. It may produce entirely new structures: + +* new wetlands, +* new ecological niches, +* new species assemblages, +* new economic opportunities, +* new social institutions. + +Likewise, peer production networks exhibit emergence: + +* new projects, +* new roles, +* new norms, +* new governance structures. + +These cannot be predicted from individual events. + +## **Proposed additions** + +### Regime emergence + +We already have: *regimeState*, *resilience* and *tippingThreshold*. We can also add *emergentProperties* or *emergenceIndicators*. Examples: + +River: + +* biodiversity index +* trophic complexity +* habitat diversity + +OVN: + +* contributor diversity +* innovation diversity +* project diversity + +These are not resources. They are emergent system-level properties. This would move the ontology closer to complexity science. + +### Adaptive capacity + +Resilience and adaptive capacity are not identical. Resilience measures persistence. Adaptive capacity measures ability to discover new configurations. A forest may be resilient but incapable of transformation. A peer network may be highly adaptive despite low stability. Therefore, *resilience*, *adaptiveCapacity* should probably be separate attributes. This comes directly from resilience theory and Panarchy. + +### Knowledge as a source + +This is an exciting one. The watershed example naturally leads to ecological sources. But OVN and P2P systems revolve around another type of source: knowledge commons. Consider open-source codebase, Wikipedia, Design repository, Scientific knowledge commons. These are also generative, non-rival, stewarded, not reducible to resources. In fact they satisfy almost every property of the Source-NDO. So perhaps the Source ontology should be generalized: + +| Source type | Examples | +| :---- | :---- | +| Ecological source | Watershed, forest | +| Knowledge source | Repository, design commons | +| Social source | Community, network | +| Cultural source | Language, traditions | + +This would connect ecological commons and knowledge commons within the same framework. That would be a major contribution to P2P economics. + +### Source metabolism + +Complexity economics often views economies as evolving ecologies. Ecologies have metabolism. A source therefore might have: + +* inflows, +* outflows, +* regeneration rate, +* decay rate, +* carrying capacity. + +Not merely inventory. Not merely stock. But metabolism. This language is much closer to ecological economics and complexity science than traditional accounting. + +## **The strongest complexity-economics interpretation** + +If I were to express the Source-NDO in a single sentence within the context of complexity economics, I would say: + +*The Source-NDO extends complexity economics beyond networks of adaptive agents by introducing generative, non-ownable, adaptive sources as first-class participants in economic systems, allowing economic activity to be modeled as a recursive process embedded within larger ecological, knowledge, and social commons.* + +That is potentially a significant step because complexity economics has become very good at modeling interactions among agents, while the Source-NDO begins to model the generative substrates from which agents, resources, and opportunities continuously emerge. In that sense, the Source-NDO is not merely an environmental accounting innovation. It may be the sitting at the foundation of **commons-centric complexity economics**, where the primary unit of analysis is neither the firm nor the market nor even the agent, but the evolving generative commons that make economic activity possible. This also aligns remarkably well with the Sensorica argument that the next stage beyond hierarchy is networked collective intelligence: the Source-NDO provides a way to anchor that collective intelligence to the commons it depends on and regenerates. + +# VALUE + +The value question touches the intersection of: + +* OVN's theory of value, +* ecological economics, +* complexity economics, +* and the Source-NDO ontology. + +*Ecological value* is often defined in ways that are incompatible with the OVN approach. Most ecological economics literature tends to define ecological value as: + +* monetary value of ecosystem services, +* willingness-to-pay, +* replacement cost, +* natural capital value. + +The OVN definition of value is fundamentally different. In OVN, value is not a property of a thing, it emerges from the relationship between an agent and something that affects the agent's goals, needs, viability, or capacity to act. Thus, ecological value cannot literally reside in the watershed, river, forest, or fish population. Instead: + +*Ecological value is the capacity of an ecological source to contribute to the viability, adaptive capacity, and flourishing of agents and agent networks.* + +This is much closer to a complexity-oriented interpretation. + +NOTE: pay attention because according to OVN value is related to agents and their relations, it is not in the thing. Therefore, the economy becomes a human thing. Those who want to include nature in the economy cause a problem. Nature cannot have a *value experience*. The economy is a human thing. So there must be a separation. We must maintain an ontological separation, the dualism nature-economy persists. We can include nature in the economy, but by other means… + +## Ecological Value in OVN Terms + +### **Definition** + +*The contribution of an ecological Source to the maintenance, regeneration, resilience, and evolutionary potential of a socio-ecological system.* + +Notice that: + +* the *Source* is not valuable in itself, +* value emerges through relationships, +* value is dynamic, +* value depends on context, +* value can differ across agents. + +This is fully aligned with the OVN theory of *value*. + +## First Dimension: Sustenance Value + +This is closest to conventional ecosystem services. + +**Examples**: + +* water provision +* food provision +* timber +* pollination +* climate regulation + +**Question**: + +How much does the *Source* support the ongoing functioning of agents? + +**Metrics**: + +* water availability +* biomass production +* fish population +* pollination rates +* nutrient cycling + +**Watershed example**: + +River → provides water +Forest → regulates water cycle + +## Second Dimension: Regenerative Value + +This dimension is usually absent from economics. A *Source* is valuable because it can regenerate itself and other sources. + +**Example**: + +* Forest → restores soil +* Wetland → restores water quality +* Mangrove → restores fisheries + +**Metrics**: + +* regeneration rate +* soil formation rate +* nutrient recovery rate +* carbon sequestration rate + +This aligns naturally with the Source-NDO notion of: + +Source → conditions → Source + +## Third Dimension: Resilience Value + +This is where complexity economics enters. A source contributes value because it stabilizes the broader system. + +**Example**: + +* Wetland absorbs floods. +* Forest buffers droughts. +* Biodiversity absorbs shocks. + +**Metrics**: + +* biodiversity +* redundancy +* connectivity +* response to disturbance + +A river with the same water volume can have radically different resilience *value*. + +## Fourth Dimension: Adaptive Capacity Value + +This goes beyond resilience. + +Resilience asks: + +Can the system survive? + +Adaptive capacity asks: + +Can the system evolve? + +Examples: + +* genetic diversity +* species diversity +* habitat diversity +* knowledge diversity within stewardship communities + +Metrics: + +* diversity indices +* network diversity +* innovation potential + +This is strongly aligned with complexity economics. + +## Fifth Dimension: Generative Value + +This is probably the most important dimension for the Source-NDO framework. The Source is fundamentally generative, it creates possibilities. + +A watershed generates: + +* water +* fish +* recreation +* tourism +* agriculture +* cultural meaning +* future opportunities + +Many of these do not yet exist. Traditional economics struggles with this because future possibilities are not inventory. Generative value measures *the capacity of a source to produce future value experiences.* + +**Metrics** (potential indicators): + +* ecosystem complexity +* biodiversity +* ecological connectivity +* carrying capacity +* emergence indicators + +## Sixth Dimension: Commons Value + +This dimension emerges directly from OVN and Nondominium. A source has value because it serves as shared infrastructure. + +**Examples**: + +* watershed +* atmosphere +* forest +* open-source design repository + +**Question**: + +How many agents depend on it? + +**Metrics**: + +* number of dependent agents +* diversity of dependent agents +* dependency ratio +* criticality + +This resembles infrastructure value. + +## Seventh Dimension: Learning Value + +This is rarely discussed. Complex adaptive systems continuously generate information. + +A watershed is also: + +* a sensor, +* an experiment, +* a knowledge generator. + +**Examples**: + +* environmental monitoring +* scientific research +* indigenous knowledge +* adaptive governance + +**Metrics**: + +* observations generated +* knowledge produced +* model improvements +* governance improvements + +This is highly compatible with the OVN emphasis on knowledge commons. + +## A Complexity-Oriented Ecological Value Vector + +We would propose: + +Ecological Value +\= +( +Sustenance, +Regeneration, +Resilience, +Adaptation, +Generation, +Commons, +Learning +) + +or + +EV \= +(S,R,Rs,A,G,C,L) + +The key insight is: *Ecological value is multidimensional and cannot be collapsed into one number without losing critical information.* This is very consistent with complexity economics. + +# Relation to the Source-NDO + +The current Source-NDO already contains some relevant attributes: + +currentStock +fluxRate +assimilationCapacity +resilience +regimeState + +We would extend it with: + +adaptiveCapacity +generativeCapacity +dependencyIndex +knowledgeValue + +Then *ecological value* becomes something computed from Source state rather than something attached to extracted resources. This is a significant departure from both traditional economics and ecosystem service accounting. + +## The deeper synthesis with OVN + +The deepest alignment with the OVN value theory may be this: + +Traditional economics tends to ask: *What is the value of the forest?* + +OVN asks: *How does interaction with the forest affect agents?* + +The Source-NDO introduces a third perspective: *What capacities does the forest possess that enable future value experiences for present and future agents?* + +This shifts attention away from pricing outputs and toward stewarding generative capacities. + +In a *complexity-oriented P2P economy*, that may become the central economic question: not "*How much value was extracted?*" but *"How much generative capacity was maintained, enhanced, or degraded?"* The *ecological value* of a Source is therefore best understood as the ***state of its generative capacities across multiple dimensions*** rather than as a monetary quantity or a stock of ecosystem services. + +# NATURE AS AGENT + +Let’s explore this beyond ontology design and enter philosophy, law, governance, and complexity science. + +We believe that Nature is important, therefore it should be represented. At the same time, the movement that advocated the “Rights of Nature” is based on a wrong assumption. Nature is real and critically important, but it belongs to a fundamentally different ontological category than agents. The Source-NDO proposal gains strength precisely because it avoids reducing nature either to a resource or to a person. + +## 1\. The Common Category Error + +The underlying issue is a classic category error. Gilbert Ryle introduced the notion of a category mistake: *treating something as belonging to a logical category to which it does not belong*. + +Examples: + +* asking what color the number seven is, +* treating a corporation as a biological organism. + +Our ontology contains at least three distinct categories: + +| Category | Examples | +| ----- | ----- | +| Agent | person, organization | +| Source | river, watershed, forest | +| Resource | water, timber, fish | + +Confusion arises when one category is forced into another. + +## 2\. Nature as Agent + +The environmental narrative often personifies nature as Mother Earth, Gaia, Nature is angry, the planet is punishing us, the river wants to flow freely, etc. Such language can be emotionally powerful and politically useful, but taken literally it creates conceptual problems. The Earth does not form intentions, deliberate, choose goals, negotiate, experience emotions, assign responsibility. A drought is not revenge. A flood is not punishment. A wildfire is not moral judgment. These are physical processes emerging from interactions among atmosphere, vegetation, hydrology, climate, geology, human interventions. Complexity theory actually reinforces this point as complex systems generate emergent behavior without intention. A hurricane, a watershed or an ecosystem does not decide. + +## 3\. Corporation as Person + +A strikingly similar process occurred with corporations. Historically corporations were viewed as legal instruments, contractual structures or organizational technologies. Over time many jurisdictions adopted the notion of corporate personhood. A corporation became a "legal person." Initially this was a practical shorthand, it allowed corporations to sign contracts, own property and appear in court. As a legal fiction, this was useful. The problem emerged when the fiction became reified. People began speaking as if corporations genuinely possessed properties of natural persons. + +### The Contradiction + +A corporation possesses assets, contracts and governance structures, but it lacks consciousness, subjective experience, suffering, moral responsibility. Only actual humans possess those. Yet personhood language encourages treating corporations as if they possessed both.This creates paradoxes. + +### Observed Consequences + +#### **Separation of power and responsibility** + +Corporations accumulate rights, assets and influence, while responsibility becomes diffused among shareholders, executives, employees and contractors. The "person" can act. Yet the person cannot suffer. This creates asymmetry. + +#### **Political distortions** + +Corporate personhood has enabled corporations to claim protections originally intended for human beings. The most cited example is the extension of constitutional protections to corporations in some jurisdictions. The legal fiction gradually acquires political reality. + +#### **Moral confusion** + +When an oil company pollutes a river, people say *the corporation did it*, but corporations do not possess minds. Actual decisions were made by boards, executives, investors and managers. The legal person can obscure the human causal chain. + +## 4\. Rights of Nature and Ecological Personhood + +A parallel movement now exists around rivers, forests, and ecosystems. Examples include: + +* Whanganui River +* Atrato River +* constitutional rights of nature in Ecuador + +These developments emerge from legitimate concerns about environmental destruction, inadequate legal protection and failures of traditional property systems. The motivations are understandable, however, the solution often introduces another category mistake. + +## 5\. What Happens When Nature Becomes an Agent? + +If a river is classified as an agent, several conceptual problems appear. + +### Problem 1: Agency without intention + +Agents normally possess preferences, goals, decision-making capability. A river possesses none of these. Therefore its "agency" must be represented by humans. Immediately the question arises: Which humans, scientists, Government, indigenous groups, NGOs, residents, future generations? The river itself never answers, humans answer on its behalf. The river becomes a rhetorical proxy. + +### Problem 2: Representation paradox + +The more nature is treated as an agent, the more human representatives gain power. Ironically, personified nature often leads to increased human mediation. The river never speaks, representatives do. This can conceal political interests behind ecological language. + +### Problem 3: Responsibility paradox + +If a river becomes an agent, can it bear responsibility, can it violate obligations, can it be negligent, can it enter reciprocal agreements. The answer is generally no. Thus ecological personhood often grants rights without corresponding capacities. This differs from ordinary agency. + +### Problem 4: Complexity distortion + +Complex systems do not act through centralized intentions. A watershed is distributed, emergent, multi-scalar and adaptive. Personification implicitly suggests a unified actor. Complexity science suggests the opposite. The watershed is not a subject. It is a system. + +## 6\. Why Source Is a Better Category + +The Source concept avoids both errors. Nature is not reduced to a ***resource***, which implies extraction. It is also not reduced to an ***agent***, which implies intention. Instead **Source** captures what ecosystems actually are. A Source generates, conditions, constrains, enables, absorbs, transforms, regenerates. These are causal capacities, not intentions, preferences, emotions or ownership claims. + +## 7\. Complexity Economics Perspective + +Complexity economics already moved beyond the notion that only agents matter. It recognizes networks, institutions, infrastructures, ecosystems, emergent structures. Yet most economic ontologies still force everything into *agent* or *resource*. The Source-NDO introduces a third category. This aligns better with complex systems thinking. A watershed is not an *agent* nor a *resource*. It is a *Generative Complex System* or a *Source*. This is a more precise ontological description. + +## **The Deeper Conclusion** + +The historical experience of corporate personhood provides a warning. A legal fiction introduced as a practical shortcut gradually became mistaken for an ontological reality. The result was persistent confusion about rights, responsibility, accountability and power. Environmental personhood risks creating a parallel confusion. The intention, to protect nature, is understandable and often laudable. But the conceptual tool may be flawed because it assigns agency where there is none. The Source-NDO offers an alternative path. Instead of personifying nature, it recognizes nature as a distinct category of entity: + +*neither resource nor person, neither property nor agent, but a generative source whose dynamics condition economic activity and whose stewardship requires governance without ownership.* + +This is arguably more consistent with complexity science, ecological reality, and the principles of nondominium. It preserves the causal importance of ecosystems without importing anthropomorphic assumptions, and it allows governance systems to be attached to ecological systems without pretending that rivers, forests, watersheds, or the Earth possess intentions, preferences, emotions, or moral agency. In that sense, the Source concept is not merely an ontology extension; it is a corrective against two centuries of conceptual oscillation between treating nature as an object to be exploited and treating nature as a person to be represented. It proposes a third category that is closer to what complex ecological systems actually are. + diff --git a/documentation/requirements/post-mvp/project-type-ndo-specifications.md b/documentation/requirements/post-mvp/project-type-ndo-specifications.md index 3b6de9b..fcade8c 100644 --- a/documentation/requirements/post-mvp/project-type-ndo-specifications.md +++ b/documentation/requirements/post-mvp/project-type-ndo-specifications.md @@ -3,6 +3,7 @@ **Status**: Post-MVP Requirements **Created**: 2026-06-16 **Relates to**: [`ndo_prima_materia.md`](../ndo_prima_materia.md), [`resources.md`](../resources.md), [`open-know-how-iopa.md`](open-know-how-iopa.md), [`digital-resource-integrity.md`](digital-resource-integrity.md), [`ndo-versioning.md`](ndo-versioning.md), [`fractal-composable-resource-architecture.md`](fractal-composable-resource-architecture.md) +**Sibling NDO type**: [`source-ndo-requirements.md`](source-ndo-requirements.md) — Source-NDO covers generative ecological systems (watersheds, rivers, forests) that yield resources and receive ecological effects. Where project-type NDOs specify *design intent*, Source-NDOs specify *generative ecological conditions*. Both use the NDO three-layer model and governance-as-operator pattern; Source-NDOs add an adaptive cybernetic governance loop and the `vf:Source` ValueFlows extension. **External references**: [OSHWA — Best Practices for Open Source Hardware 1.0](https://oshwa.org/resources/sharing-best-practices/), [Open Know-How Specification (IOPA)](https://iopa.pubpub.org/pub/okh) --- @@ -441,4 +442,25 @@ Project-type NDOs often correspond to **Project** collective agents ([`REQ-NDO-A --- +--- + +## 12. Sibling NDO Type: Source-NDO + +A **Source-NDO** is a sibling specification type that governs *generative ecological systems* (watersheds, rivers, forests, fisheries) and *knowledge commons* rather than design artefacts in development. While project-type NDOs specify design intent — what a thing is supposed to be and how to fabricate it — Source-NDOs specify generative ecological conditions: what a source yields, what effects it receives, how its condition evolves, and how governance rules must adapt as its event ledger accumulates. + +Key differences: + +| Dimension | Project-type NDO | Source-NDO | +|---|---|---| +| Represents | Resource in development (design → production) | Generative ecological system (watershed, fishery) | +| Layer 1 content | `SpecificationPackage` — OSHWA/OKH artifacts | `SourceSpecification` — boundary conditions, monitoring framework | +| Governance pattern | Rule evaluation at transition request | Adaptive cybernetic loop: events → interpretation → rule revision → conditioned events | +| Custodian | `primaryAccountable` (custody, not ownership) | `stewardedBy` — stewardship obligations, no ownership | +| PropertyRegime | Any | `Nondominium` or `CommonPool` only | +| ValueFlows extension | Standard VF events | `vf:Source` flow endpoint role | + +Normative requirements for Source-NDO are in [`source-ndo-requirements.md`](source-ndo-requirements.md). + +--- + *This is a normative post-MVP requirements document. Implementation shall not contradict [`ndo_prima_materia.md`](../ndo_prima_materia.md) REQ-NDO-* IDs. When OSHWA or Open Know-How standards update, §4 field mappings should be revised without changing the underlying NDO architectural invariants (Layer 0 identity, Layer 1 spec + DigitalAsset slots, governance-as-operator).* diff --git a/documentation/requirements/post-mvp/source-ndo-paper.md b/documentation/requirements/post-mvp/source-ndo-paper.md new file mode 100644 index 0000000..ae8ea37 --- /dev/null +++ b/documentation/requirements/post-mvp/source-ndo-paper.md @@ -0,0 +1,289 @@ +# Source-NDO: Making Nature Visible in Economic Information Systems + +## Abstract + +Ecological degradation is usually described as a policy failure, a market failure, or a moral failure. It is also an information-system failure. Many effects of economic activity are called "externalities" because they do not appear inside the transaction record that coordinates economic agents. Pollution, depletion, regeneration, and ecological condition are often measured elsewhere, after the fact, by regulators, scientists, or affected communities. This paper proposes a new economic-information primitive, the **Source**, implemented as a **Source-NDO**: a generative, non-ownable, partially unknowable ecological system whose boundary events can be recorded, whose condition can be sensed, and whose access rules can adapt through stewardship governance. The Source is neither an Agent nor a Resource. A river does not deliberate or bear responsibility like an agent, but it is also not merely an owned stock of water. It is a generative system that yields resources, receives ecological effects, conditions other sources, and makes future economic activity possible. By extending event-based economic ontologies such as REA and ValueFlows with this primitive, externalities can become first-class economic events without reducing nature to property, capital, or legal personhood. + +## 1. Externalities As Information Failure + +Economic activity changes ecological systems. Farms withdraw water and release nutrients. Mines consume water and discharge heavy metals. Dams use river flow without consuming it but alter timing, sediment, and downstream access. Forest operations remove trees and change infiltration, erosion, and biodiversity. Restoration groups replant riparian zones, rebuild wetlands, and improve the regenerative capacity of the watershed. These acts are economic, but the ecological effects are often not recorded in the same information system that records the transaction. + +The classical language for this problem is externality. Pigou framed it as a divergence between private and social net product: economic actors are interested in the private result of their operations, while some benefits or harms fall on others without compensation (Pigou, 1920/1932). Coase later reframed the problem through rights, reciprocal harm, and transaction costs, insisting that institutions matter because real parties do not bargain in a frictionless world (Coase, 1960). Both traditions remain useful. But both leave open a prior question: where, in the economic information system, does the ecological effect appear? + +If a factory sells a product, the sale appears in accounting. If a farm buys water rights, the contract appears. If a city utility pays for treatment, the cost appears. But the river's changing assimilation capacity, the wetland's reduced flood-buffering capacity, or the forest's effect on downstream flow may appear only in environmental reports, scientific models, or public controversy. The economic ledger and the ecological ledger are separated. The "externality" is external not only to price but also to the record of economic coordination. + +The purpose of this paper is to propose a way to change that record. We need economic information systems that make ecological effects visible without forcing nature into categories that distort it. The challenge is not simply to attach a price to nature, nor to declare nature a person, nor to create more reports. The challenge is to represent natural systems as entities around which economic activity, ecological monitoring, and adaptive governance can be coordinated. + +## 2. Why Existing Categories Are Not Enough + +Several traditions already make nature visible, and this paper builds on them. Ecosystem-services research showed that human economies depend on functions that ecosystems perform: water purification, pollination, flood regulation, soil formation, climate regulation, and much more. Daily's *Nature's Services* helped consolidate this framing (Daily, 1997), and Costanza et al. famously estimated the value of global ecosystem services and natural capital in *Nature* (Costanza et al., 1997). The Millennium Ecosystem Assessment and TEEB brought ecosystem services into policy language. The UN System of Environmental-Economic Accounting--Ecosystem Accounting (SEEA EA), adopted by the UN Statistical Commission in 2021, now provides the strongest official accounting framework for ecosystem extent, condition, physical service flows, monetary service flows, and ecosystem assets (United Nations et al., 2021). + +Ecological economics adds a deeper warning. Georgescu-Roegen argued that the economic process is embedded in the entropy-bound material world, not in a closed circular flow of exchange (Georgescu-Roegen, 1971). Daly later framed the economy as a subsystem of a finite biosphere and emphasized throughput limits (Daly, 1977/1991). These traditions make clear that ecological systems are not optional background conditions. They are the generative basis and sink environment of economic life. + +This is important work. It makes nature visible to economics and policy. Yet most of it remains descriptive. SEEA EA can tell us how ecosystem extent and condition are changing, and ARIES for SEEA can help compile ecosystem accounts through semantic modeling and data integration. But an account is not yet a governance object. It does not itself condition future economic events. It does not say: this mine can discharge only this much this month; this farm's abstraction is reduced because upstream forest loss has lowered flow resilience; this restoration work increases future access capacity. The account informs policy, but the policy remains outside the accounting object. + +Commons governance gives us another crucial foundation. Ostrom showed that communities can govern common-pool resources without defaulting to either privatization or centralized command. Her design principles emphasize clear boundaries, monitoring, graduated sanctions, conflict-resolution mechanisms, and nested institutions (Ostrom, 1990). Later social-ecological systems (SES) work distinguishes resource systems, resource units, governance systems, and users (Ostrom, 2009). This distinction is close to the one we need. A forest is not the same as timber; a fishery is not the same as fish; a watershed is not the same as gallons of water. + +But in SES theory, the resource system is primarily an analytical object. Researchers and practitioners use it to diagnose sustainability. It is not usually an executable object inside an economic information system. It does not itself receive economic events, accumulate a ledger, or carry machine-readable governance rules. + +Rights of Nature and ecological personhood respond to a related failure. Ecuador's Constitution recognizes the rights of nature, or Pacha Mama, including respect for existence and the maintenance and regeneration of life cycles. The Te Awa Tupua Act declares the Whanganui River a legal person: "Te Awa Tupua is a legal person and has all the rights, powers, duties, and liabilities of a legal person" (Te Awa Tupua Act, 2017, s. 14). These are serious legal innovations. They emerge from real failures of property law and environmental regulation, and they should be treated with respect. + +Yet legal personhood is not the same as economic ontology. A river does not deliberate, commit, form intentions, or bear responsibility. Its legal powers must be exercised by human representatives. That may be practical in law, but it creates problems if imported directly into economic information systems. The risk is a category error: nature is not merely a resource to be consumed, but it is also not an agent in the same sense as a person, cooperative, firm, or state. + +Event-based economic ontologies such as REA and ValueFlows bring us closer to implementation. McCarthy's REA model shifted accounting toward Resources, Events, and Agents as economic primitives in shared data environments (McCarthy, 1982). ValueFlows extends this style of modeling for open and networked economic coordination. It can represent economic resources, economic events, agents, commitments, claims, processes, and resource specifications. This is exactly the kind of infrastructure needed for commons-oriented economic systems. + +But if we try to model nature using only Agent and Resource, we hit a boundary. A river is not honestly an owned economic resource, and it is not honestly an agent. Something is missing. + +## 3. Agent, Resource, Source + +The missing primitive is **Source**. + +An **Agent** is an entity that can act, intend, commit, deliberate, accept obligations, and bear responsibility. In economic information systems, agents can be individuals, organizations, networks, cooperatives, and perhaps delegated artificial agents whose scope and operator are declared. The crucial point is agency: the ability to participate in commitments and governance. + +A **Resource** is an appropriable or inventoriable output used in economic processes: water abstracted into a tank, timber cut into planks, fish landed at a dock, electricity delivered to a meter, data stored in a repository, or a tool held in custody. Resource accounting is necessary. Once water is abstracted, fish are caught, or timber is cut, those things can be counted, transferred, consumed, used, or transformed. + +A **Source** is different. A source is a generative system that yields resources, absorbs effects, conditions future possibilities, regenerates or degrades, and interacts with other sources. A watershed yields river flow; a forest conditions infiltration, biodiversity, and soil stability; a wetland absorbs flood peaks and pollutants; a fishery yields fish only if its biological regime remains viable. A source is not merely a stock behind a flow. It is a complex system whose generative capacity makes economic activity possible. + +The Source category avoids two reductions. It avoids reducing nature to a Resource, which frames the river mainly as inventory or service flow. It also avoids reducing nature to an Agent, which imports intention where there is none. A river can provide water, receive pollution, condition fish populations, and alter economic possibilities. But it does not negotiate, promise, consent, or take responsibility. The Source is therefore a third category: neither resource nor person, neither property nor agent, but a generative ecological entity around which stewardship can be organized. + +This may sound like a small terminological change, but classifications matter. Bowker and Star argue that classification systems and standards shape infrastructure, visibility, and power (Bowker & Star, 1999). If an information system has no category for a generative ecological source, certain relations remain invisible or must be represented through fictions. If it does have such a category, new forms of accounting and governance become possible. + +## 4. Complexity And The Black-Box Principle + +The Source primitive is not only an ontological proposal. It also carries an epistemological stance. + +Watersheds, forests, fisheries, soils, and atmospheres are complex systems. Holling's work on ecological resilience challenged equilibrium-centered views of ecosystems and made persistence under disturbance central to ecological thinking (Holling, 1973). Panarchy extended this into cross-scale adaptive cycles (Gunderson & Holling, 2002). Adaptive governance literature emphasizes learning, bridging organizations, trust, and transformation under disturbance (Folke et al., 2005). These systems are partially knowable, nonlinear, path-dependent, multi-scalar, and capable of regime shifts. + +The implication is not that we need infinite data before governing. It is the opposite. We must stop pretending that governance requires a complete model of the ecological interior. + +Ashby's cybernetics gives us a useful language. Some systems are too large, inaccessible, or complex to inspect directly; they must be treated as black boxes whose behavior is studied through inputs, outputs, and responses (Ashby, 1956). Scott's critique of high-modernist planning gives the political warning: attempts to make nature and society legible for centralized control often simplify away the practical and ecological relations that matter (Scott, 1998). Cynefin gives the operational pattern: in complex domains one does not predict, plan, and control; one probes, senses, and responds (Snowden & Boone, 2007). + +The Source-NDO adopts this stance. It does not try to model the full interior of a watershed. It records boundary events and condition signals. Trees cut, gallons abstracted, pollutants discharged, fish caught, wetlands restored, riparian buffers planted, sediment loads measured, biodiversity indicators updated. The governance object does not claim omniscience. It asks for a disciplined loop: + +observe boundary events, sense source condition, interpret through science and situated knowledge, adapt governance rules, condition future access, and learn from the next round of events. + +This is not a weakness of the model. It is the model's integrity. It refuses to reduce ecological complexity to false precision. + +## 5. A River Case + +Consider a watershed feeding a river. The river participates in a contested economic ecosystem. An agricultural cooperative abstracts water and contributes nutrient runoff. A city utility depends on clean water downstream. A mining company consumes water and discharges effluent. A hydro dam uses flow without consuming water but changes timing and sediment dynamics. Fishers extract fish. Tour operators use the river for recreation and transport. A forestry operation removes trees in the watershed, affecting infiltration and flow stability. A regeneration collective restores riparian zones and wetlands. + +ValueFlows 1.0 can model many of the economic events well once the outputs have become resources. Water in the cooperative's tank is an EconomicResource. Fish landed by the fishing guild are EconomicResources. Timber cut into planks is an EconomicResource. Events such as use, consume, produce, transfer, work, and transport are useful and should be kept. + +The problem is the river itself. + +If the river is modeled as an EconomicResource, the system tends to ask who is primary accountable, who owns or controls the resource, or who bears the rights and responsibilities over it. In a nondominium regime, this is precisely the wrong move. The river is not owned by a steward organization. A steward may hold obligations, but stewardship is not dominium. + +If the river is avoided as a resource, water abstraction may appear as a `raise` event in the receiver's inventory: water appears in AgriCoop's stock because it has been "found" or "raised." But then the river is not debited. Depletion disappears from the economic record. + +Pollution creates another contradiction. If MiningCo discharges heavy metals, the river is the ecological receiver. But if the river is only a resource, it cannot receive an event in the way an agent can. If the river is typed as an ecological agent, then the system gives it agency it does not possess. The same entity is pushed into two incompatible categories: resource for extraction, agent for pollution. + +The Source primitive removes these fictions. The event can be represented honestly: + +```text +EconomicEvent: + action: extract + provider: River(Source) + receiver: AgriCoop(Agent) + quantity: 10000 m3 water +``` + +The river is debited as a source, not as an owned resource. Pollution can also be represented honestly: + +```text +EconomicEvent: + action: produce/discharge + provider: MiningCo(Agent) + receiver: River(Source) + quantity: 50 kg heavy metals +``` + +Regeneration becomes visible: + +```text +EconomicEvent: + action: restore/raise + provider: RegenCollective(Agent) + target: RiparianForest(Source) + result: improved infiltration and reduced sediment loading +``` + +Source-to-source coupling also becomes visible. The forest conditions the river. The wetland conditions flood buffering and water quality. The river conditions fish populations. The source web is not an external report; it becomes part of the accounting graph. + +The result is more parsimonious than forcing nature into existing categories. Adding one primitive removes several fictions: false ownership, resource-from-nowhere, river-as-agent, missing source hierarchy, missing source coupling, and missing object-attached governance. Occam's razor does not merely count vocabulary terms. It asks whether the theory multiplies ad hoc assumptions. Here, the Source primitive adds one term but removes a much larger number of fictions. + +## 6. From Visibility To Stewardship + +Visibility alone is not enough. A report can say that a river is degraded while the next transaction proceeds unchanged. The Source-NDO proposal matters because it connects the event ledger to adaptive governance. + +The loop is: + +```text +events -> ledger -> ecological interpretation -> governance rules -> access affordances -> future events +``` + +Extraction becomes visible as an event from the Source to an Agent. Pollution becomes visible as an event from an Agent to the Source. Regeneration becomes visible as work that improves source condition or generative capacity. Cross-source coupling becomes visible when one source conditions another: forest loss lowers river resilience; wetland restoration increases flood buffering; biodiversity affects fishery stability. + +Governance can then condition future access. If nutrient runoff exceeds thresholds, agricultural abstraction may require remediation commitments. If forest loss reduces infiltration, downstream water quotas may change. If restoration improves riparian condition, access constraints may adapt. If uncertainty is high, precautionary buffers can be increased. This is not static command-and-control. It is adaptive stewardship anchored in an object that accumulates its own history. + +In this sense, the Source-NDO extends Ostrom into more complex ecological domains. Ostrom's commons governance gives us monitoring, sanctions, conflict resolution, and nested institutions. But many ecological systems are not merely complicated resource systems whose rules can be designed once from adequate knowledge. They are complex systems whose responses are uncertain and evolving. The Source-NDO treats rules as revisable governance attached to a source ledger. + +## 7. Ecological Value Without Reducing Nature To Price + +Because the paper proposes a new economic object, it must also be careful about value. The aim is not to replace the price of ecosystem services with another single number. The IPBES Values Assessment emphasizes the diverse values of nature, including instrumental, intrinsic, and relational values (IPBES, 2022). Costanza has also argued that valuation should be related not only to efficiency but also to fairness and sustainability (Costanza, 2000; Costanza et al., 2020). + +In OVN terms, value is relational. It is not simply inside a thing. It emerges in relation to agents, needs, capacities, viability, goals, and future possibilities. A river does not "experience value." But the river has capacities that make value experiences possible for present and future agents. Therefore ecological value is best understood as the contribution of a Source to the maintenance, regeneration, resilience, adaptive capacity, and flourishing of socio-ecological systems. + +This suggests a value vector rather than a single price: + +Sustenance: water, food, materials, pollination, climate regulation. + +Regeneration: soil formation, water purification, biomass recovery, carbon sequestration. + +Resilience: buffering shocks, maintaining function under disturbance, avoiding regime collapse. + +Adaptive capacity: diversity, connectivity, and the ability to discover new viable configurations. + +Generative capacity: the ability to produce future resources, relations, opportunities, and meanings not yet known. + +Commons value: the number and diversity of agents that depend on the source as shared infrastructure. + +Learning value: observations, knowledge, models, and governance improvements generated through interaction with the source. + +The key point is that ecological value is not exhausted by extracted resources. The central question becomes: how much generative capacity was maintained, enhanced, or degraded? That question is more appropriate for complex ecological sources than "how much value was extracted?" + +## 8. Implementation: Source-NDO + +The full usefulness of the Source primitive appears only when it is implemented inside an information infrastructure able to make a source persistent, uncapturable, governed, and accountable without making it owned. This is why Nondominium matters. The Nondominium hApp is built on Holochain and uses the ValueFlows vocabulary, but its distinctive contribution is not merely a new database schema. It is an architecture for organization-agnostic, governance-bearing objects on a distributed hash table (DHT). + +In the current Nondominium design, an NDO begins with a Layer 0 identity anchor, `NondominiumIdentity`. This entry contains a name, initiator, property regime, resource nature, lifecycle stage, creation time, and description. Its action hash becomes the stable identifier of the object. In Holochain terms, this is not a record in a platform database controlled by an administrator; it is an entry on an agent-centric source chain, published and linked into the DHT for discovery. The object is found through DHT links and anchors, not through a central owner's table. This matters for commons and nondominium property regimes because the object is no longer dependent on one organization to continue existing. No platform operator can simply delete the source from a private database, and no single steward can convert its identity into private property by administrative command. + +For a Source-NDO, this means a river, forest, wetland, watershed, or fishery can receive a persistent economic-information identity without becoming an asset owned by the organization that first registered it. The source can be discoverable, linkable, auditable, and governed while remaining organization-agnostic. This is the technical condition that makes nondominium more than a legal or moral declaration. The source becomes difficult to enclose because its identity, history, and governance relations are distributed across the network. + +The second crucial feature is NDO-embedded governance. In Nondominium, governance rules are attached to the resource specification or, in the NDO model, to the object itself as it grows from identity to specification and process. Access and interaction rules are not merely external policies stored in a manual, a government database, or an organization's internal workflow. They become part of the object's operational surface. An agent does not simply ask a platform for permission to use a source; the agent interacts with an object whose rules travel with it. + +For a Source-NDO, this is essential. A watershed cannot be governed well if every interaction is interpreted separately by disconnected institutions. The rules for abstraction, loading, remediation, monitoring, restoration, buffer requirements, or seasonal restrictions need to be attached to the source being affected. This gives the Source-NDO a kind of accessibility autonomy. It is not autonomous in the sense of having agency or intention. It is autonomous in the infrastructural sense that the conditions for access are bound to the object rather than to an owning organization. + +The third feature is governance-as-operator. The Nondominium architecture separates the resource zome, which stores data, from the governance zome, which evaluates state transitions. In the specified pattern, a proposed transition is not applied directly. It is submitted as a governance transition request; the governance module evaluates applicable rules, checks permissions and constraints, and returns a governance result. Only then can state change and related economic events be recorded. + +This separation is especially important for complex ecological sources. A Source-NDO should not change state merely because an agent writes a new value. If a river moves from "stable" to "stressed," if an extraction quota changes, or if a restoration event raises generative capacity, that change should be mediated by rules, evidence, and validation. Governance-as-operator turns the source from a passive record into a cybernetic object: events and observations feed into interpretation; interpretation updates rules or state; rules condition future events. + +Because governance is a separate architectural module, it can evolve over time. This is where the black-box principle becomes operational. Stewards do not need to know the complete interior of the watershed. They acquire peripheral data: withdrawals, pollutant loads, sensor readings, fish counts, flood events, restoration work, seasonal variation, and local observations. Governance can then adapt around these signals. As the source ledger grows, stewards can revise thresholds, add monitoring obligations, change access rules, or introduce graduated sanctions. The governance module becomes the adaptive interface between the unknowable interior of the ecological system and the economic actions occurring at its boundary. + +The fourth feature is the Private Participation Receipt system. PPRs are private, cryptographically signed participation records stored on agents' source chains. They extend ValueFlows claims with participation categories, performance metrics, signatures, counterparties, and resource references. This gives Nondominium a flexible relation between public exposure and private accountability. + +For ecological governance, that flexibility is critical. Not every stewardship action or ecological interaction should be globally public in full detail. Some information may be sensitive: locations of endangered species, sacred sites, private land-use details, personal identities, or conflict records. At the same time, governance requires proof. Agents must be able to show that monitoring happened, that remediation work was completed, that a validator participated, that a custody or restoration obligation was fulfilled, or that a disputed event was recorded at a certain time. PPRs allow agents to secure evidence of their actions while preserving privacy by default. + +This creates a powerful design space. Public policy or community governance may require some information to be publicly exposed: total withdrawals, aggregate pollutant loads, restoration events, or source-condition indicators. Other information may remain private but verifiable. In future implementations, zero-knowledge proofs can allow an agent to prove a claim about their private chain, such as "I completed five validated restoration commitments" or "this monitoring obligation was fulfilled by a qualified steward," without exposing all counterparties, notes, locations, or private records. PPRs therefore combine proof and accountability without forcing total transparency. + +Taken together, these mechanisms explain why Source becomes powerful specifically in Nondominium. ValueFlows gives the event vocabulary. Holochain gives agent-centric DHT infrastructure. Nondominium adds organization-agnostic identity, uncapturable object persistence, embedded governance, governance-as-operator, and private-but-verifiable participation records. A Source-NDO is therefore not just a concept named in a paper. It is a candidate implementation pattern for ecological sources that must be stewarded without being owned, observed without being fully modeled, and governed without central platform control. + +This combination is the paper's core contribution. Many traditions contain one part of it: commons governance, ecosystem accounting, event-based economic ontology, distributed infrastructure, and privacy-preserving accountability. Source-NDO composes them into an operational primitive for ecological-economic information systems. + +## 9. Limits And Risks + +The proposal must not be presented as a magic solution. Several risks are serious. + +Measurement quality matters. Who produces ecological data? Are sensors trustworthy? How is uncertainty represented? What happens when data is missing, delayed, or contested? - P2P offers solutions, as it is focused on validation. + +Governance legitimacy matters. Who interprets the ledger? Scientists, local communities, public agencies, indigenous authorities, resource users, or some combination? Who changes the rules? Who can challenge them? - Cosmolocalism provides answers, as knowledge remains global and decisionmaking rests with the locals. + +Local and indigenous knowledge must not be extracted and flattened into a technical schema. Berkes' work on sacred ecology and traditional ecological knowledge is a reminder that stewardship knowledge is situated, relational, and often inseparable from culture and practice (Berkes, 2012). A Source-NDO should be able to receive qualitative, narrative, and community-validated signals without pretending all knowledge is sensor data. + +Data sovereignty matters. Ecological data can expose communities, sacred sites, endangered species, or politically sensitive land-use conflicts. Visibility must be governed. + +There is also a risk of green accounting capture. Better measurement can legitimize extraction if governance remains weak. A company might say: "we recorded the damage, therefore the activity is responsible." - Source-NDO addresses this as it ties to access rules, obligations, and accountability, not only disclosure. + +Finally, legal interoperability remains open. Source-NDOs would need to interact with public law, permits, rights-of-nature frameworks, commons agreements, indigenous jurisdiction, and existing environmental reporting systems. The proposal is infrastructural, not a replacement for law or politics. + +## 10. Conclusion + +Economic systems have long struggled to include nature without reducing it. Nature appears as resource, asset, service, cost, externality, protected area, or legal person. Each category reveals something and hides something. The Source primitive proposes another path. + +A Source is a generative, non-ownable, partially unknowable system that yields resources, receives ecological effects, conditions future economic possibilities, and accumulates the evidence required for its own stewardship. A Source-NDO makes this primitive executable in an economic information system. It allows a river, forest, wetland, fishery, or watershed to become a ledger-bearing governance object without becoming property and without pretending to be a person. + +The paradigm shift is simple but deep. The economy is not only a network of agents exchanging resources. It is embedded in a wider network of generative sources. If economic information systems cannot see those sources, externalities will remain structurally external. If they can see them, then extraction, pollution, regeneration, resilience, and adaptive capacity can become part of economic coordination. Moreover, if governance is attached to these sources as an operator, a gate for economic action, we can steward them. + +The next economic question is therefore not only: how much value was extracted? It is: how much generative capacity was maintained, enhanced, or degraded? + +## References + +Ashby, W. R. (1956). *An Introduction to Cybernetics*. Chapman & Hall. + +ARIES for SEEA. (n.d.). *ARIES for SEEA Explorer*. Integrated Modelling Partnership / United Nations ecosystem accounting tooling. + +Berkes, F. (2012). *Sacred Ecology* (3rd ed.). Routledge. + +Bowker, G. C., & Star, S. L. (1999). *Sorting Things Out: Classification and Its Consequences*. MIT Press. + +Coase, R. H. (1960). The problem of social cost. *Journal of Law and Economics*, 3, 1-44. [https://doi.org/10.1086/466560](https://doi.org/10.1086/466560) + +Costanza, R. (2000). Social goals and the valuation of ecosystem services. *Ecosystems*, 3, 4-10. + +Costanza, R., d'Arge, R., de Groot, R., et al. (1997). The value of the world's ecosystem services and natural capital. *Nature*, 387, 253-260. [https://doi.org/10.1038/387253a0](https://doi.org/10.1038/387253a0) + +Costanza, R., et al. (2020). Valuing natural capital and ecosystem services toward the goals of efficiency, fairness, and sustainability. *Ecosystem Services*, 43, 101096. + +Daily, G. C. (Ed.). (1997). *Nature's Services: Societal Dependence on Natural Ecosystems*. Island Press. + +Daly, H. E. (1977/1991). *Steady-State Economics*. W. H. Freeman / Island Press. + +Ecuador. (2008). *Constitution of the Republic of Ecuador*, Articles 71-74. + +Folke, C., Hahn, T., Olsson, P., & Norberg, J. (2005). Adaptive governance of social-ecological systems. *Annual Review of Environment and Resources*, 30, 441-473. [https://doi.org/10.1146/annurev.energy.30.050504.144511](https://doi.org/10.1146/annurev.energy.30.050504.144511) + +Geerts, G. L., & McCarthy, W. E. (2002). An ontological analysis of the economic primitives of the extended-REA enterprise information architecture. *International Journal of Accounting Information Systems*, 3(1), 1-16. + +Georgescu-Roegen, N. (1971). *The Entropy Law and the Economic Process*. Harvard University Press. + +Gunderson, L. H., & Holling, C. S. (Eds.). (2002). *Panarchy: Understanding Transformations in Human and Natural Systems*. Island Press. + +Holling, C. S. (1973). Resilience and stability of ecological systems. *Annual Review of Ecology and Systematics*, 4, 1-23. [https://doi.org/10.1146/annurev.es.04.110173.000245](https://doi.org/10.1146/annurev.es.04.110173.000245) + +IPBES. (2022). *Methodological Assessment Report on the Diverse Values and Valuation of Nature*. IPBES Secretariat. + +McCarthy, W. E. (1982). The REA accounting model: A generalized framework for accounting systems in a shared data environment. *The Accounting Review*, 57(3), 554-578. + +Millennium Ecosystem Assessment. (2005). *Ecosystems and Human Well-being: Synthesis*. Island Press. + +Ostrom, E. (1990). *Governing the Commons*. Cambridge University Press. + +Ostrom, E. (2009). A general framework for analyzing sustainability of social-ecological systems. *Science*, 325(5939), 419-422. [https://doi.org/10.1126/science.1172133](https://doi.org/10.1126/science.1172133) + +Pigou, A. C. (1920/1932). *The Economics of Welfare*. Macmillan. + +Scott, J. C. (1998). *Seeing Like a State*. Yale University Press. + +Snowden, D. J., & Boone, M. E. (2007). A leader's framework for decision making. *Harvard Business Review*, 85(11), 68-76. + +Star, S. L., & Ruhleder, K. (1996). Steps toward an ecology of infrastructure: Design and access for large information spaces. *Information Systems Research*, 7(1), 111-134. [https://doi.org/10.1287/isre.7.1.111](https://doi.org/10.1287/isre.7.1.111) + +Te Awa Tupua (Whanganui River Claims Settlement) Act 2017 (NZ). + +TEEB. (2010). *The Economics of Ecosystems and Biodiversity: Mainstreaming the Economics of Nature*. + +United Nations et al. (2021). *System of Environmental-Economic Accounting--Ecosystem Accounting (SEEA EA)*. + +ValueFlows. (n.d.). *ValueFlows specification*. [https://www.valueflo.ws/](https://www.valueflo.ws/) + +## Appendix: Human-AI Collaboration Summary + +This paper was produced through a human-AI collaboration in which the human author retained the primary role in goal definition, conceptual direction, normative judgment, and final authorship authority. The AI systems contributed retrieval, synthesis, structuring, drafting, and editorial support. This division follows the collaboration framework developed at Sensorica, where AI is treated as strongest in search, aggregation, summarization, pattern expansion, drafting, and procedural workflow support, while human contribution remains central in value framing, meaning-making, contextual reframing, ethical boundary setting, responsibility, creative direction, and final approval. + +The collaboration unfolded in three broad phases: brainstorming, structuring and planning the paper, and text improvement/refinement. + +In the brainstorming phase, the human author introduced the idea of **Source** as a new primitive alongside Resource and Agent, and framed Source as a complex system. The human author also made the first observation that treating a river either as a resource or as an agent creates a category error. The intuition and initial argument against nature-as-agent also came from the human author, including the comparison between personifying nature and treating corporations as persons. AI later helped substantiate and expand this argument. + +This brainstorming phase drew on the humans' experience with the OVN model and with development of the Nondominium hApp. The human author identified the governance layer of Nondominium as the place where ecological complexity could enter the system: not by claiming complete knowledge of an ecosystem's interior, but through policy that adapts from peripheral data, source-condition signals, and information acquired through economic events. The human author also explicitly introduced the black-box idea for complex ecological systems; AI later helped find relevant references from cybernetics, complexity science, resilience theory, and adaptive governance to support that intuition. The discussion of value depended on Sensorica's definition of value in the OVN wiki, which reflects the network's collective intelligence: value is relational and emerges through agents' experiences, needs, goals, and capacities, rather than residing as a property inside objects. + +AI contributed pattern recognition, conceptual expansion, and first-pass theoretical scaffolding. It helped articulate the ecological value vector used in the paper: Sustenance, Regeneration, Resilience, Adaptive Capacity, Generative Capacity, Commons Value, and Learning Value. It also helped polish the critique of nature-as-agent: ecological systems generate effects but do not deliberate, intend, commit, feel harm, or bear moral responsibility. That exchange supplied important conceptual raw material, but the originating questions, domain constraints, value commitments, and direction of inquiry came from the human author and the prior human brainstorming. + +In the structuring and planning phase of this paper, the human author provided a first layout with 3 interlocking structures: thematic, pragmatic and logical. He also explained the intended audience, specified that the paper should help environmental practitioners, economists, policy actors, activists, and related readers understand a paradigm shift, and asked for the planning and brainstorming material to remain intact. The human author chose the paper's practical goal: making externalities visible inside economic information systems so economic agents can steward natural sources and resources. The human author also set editorial constraints: keep the paper concise, preserve conceptual depth, use references and quotations for important claims, and keep the planning file available for later revision. + +The AI contribution in this phase was to read and reorganize the planning material, strengthen the paper structure, improve the literature and prior-knowledge sections, validate and insert source anchors, and draft the paper. The AI synthesized the human-provided concepts into a more coherent essay structure: externalities as information failure; limits of existing categories; Agent, Resource, and Source; complexity and the black-box principle; a worked river case; the visibility-to-stewardship governance loop; ecological value without reduction to price; implementation as Source-NDO; and limits and risks. The AI also added references and performed coherence and diagnostic checks. + +In the text improvement and refinement phase, the human author evaluated the draft and identified a weak point in the implementation section. The human author clarified that the full power of the Source primitive only becomes visible in the context of the Nondominium hApp, and supplied the architectural concepts that needed to be made explicit: organization-agnostic NDOs on the DHT, uncapturable commons and nondominium property regimes, NDO-embedded governance, governance-as-operator, the evolution of governance as a separate module, and Private Participation Receipts as a flexible privacy/accountability mechanism. The human author also connected these concepts back to the black-box ecological model: stewards use peripheral data and economic-event information to steer a complex source toward sustainable states without pretending to fully know its interior. + +The AI contribution in this refinement phase was to inspect the Nondominium documentation and codebase, verify the current implementation status and architectural claims, and rewrite the implementation section accordingly. This included distinguishing implemented features, such as the Layer 0 `NondominiumIdentity` DHT anchor and PPR data structures, from normative architectural targets such as full governance-as-operator lifecycle integration. AI then strengthened the prose so that the implementation section explained why Source-NDO is not merely a conceptual addition to ValueFlows, but an implementation pattern made powerful by Nondominium's DHT identity, embedded governance, adaptive governance module, and private-but-verifiable participation records. + +The collaboration was therefore hybrid. The human author supplied the original problem, philosophical and political motivation, domain knowledge, conceptual constraints, and evaluative direction. AI systems supplied cognitive offloading: retrieval, condensation, comparison, structure generation, prose drafting, and consistency checking. The resulting paper should be read as human-directed and AI-assisted: the AI helped transform a complex body of prior thinking into a written form, but the central thesis, purpose, framing, and responsibility for use remain with the human author. \ No newline at end of file diff --git a/documentation/requirements/post-mvp/source-ndo-requirements.md b/documentation/requirements/post-mvp/source-ndo-requirements.md new file mode 100644 index 0000000..fcb3d99 --- /dev/null +++ b/documentation/requirements/post-mvp/source-ndo-requirements.md @@ -0,0 +1,450 @@ +# Source-NDO Requirements (Post-MVP) + +**Status**: Post-MVP Requirements +**Created**: 2026-07-01 +**Relates to**: [`ndo_prima_materia.md`](../ndo_prima_materia.md), [`resources.md`](../resources.md), [`governance.md`](../governance.md), [`requirements.md`](../requirements.md) +**Academic grounding**: [`source-ndo-paper.md`](source-ndo-paper.md) (full theoretical justification, river case study, Occam's razor proof, complexity economics analysis) +**Sibling NDO types**: [`project-type-ndo-specifications.md`](project-type-ndo-specifications.md) + +--- + +## 1. Problem Statement and Ontological Position + +### 1.1 The missing primitive + +The REA/ValueFlows economic ontology operates with two primitives: **Agent** (entities that can act, commit, deliberate, and bear responsibility) and **Resource** (appropriable, inventoriable outputs used in economic processes). A river, watershed, forest, or fishery fits neither category honestly. + +If modelled as an `EconomicResource`, the system requires a `primaryAccountable` owner — the exact inverse of the `Nondominium` property regime. If modelled as an `Agent`, it is attributed intention it does not possess; and if avoided entirely, abstraction events appear as `raise` (resource-from-nowhere) while depletion disappears from the ledger entirely. + +The academic paper (`source-ndo-paper.md`) demonstrates this with Occam's razor: without the `Source` primitive, a faithful representation of a watershed under `Nondominium` governance requires **three active fictions** (false ownership, phantom `raise`, resource/agent dual-typing for pollution receivers) and **four inexpressible relations** (source hierarchy, cross-source coupling, black-box epistemics, governance reflexivity). Adding one primitive removes all seven. + +**`Source` is therefore a third ontological primitive**: neither resource nor person, neither property nor agent, but a generative, non-ownable, partially unknowable system that yields resources, receives ecological effects, conditions future possibilities, and accumulates the historical evidence required for its own stewardship. + +### 1.2 Ostrom mapping + +The Source/Resource distinction has a direct lineage in Elinor Ostrom's Social-Ecological Systems framework: + +| Ostrom / SES concept | Source-NDO equivalent | +|---|---| +| Resource system (e.g. fishery, watershed) | **Source** | +| Resource unit (e.g. fish, gallons of water) | **Resource** (`EconomicResource`) | +| Governance system | Object-attached `GovernanceRule` entries (governance-as-operator) | +| Users / actors | **Agents** | +| Action situation | Economic events, commitments, claims | + +The Source-NDO operationalises Ostrom's analytical categories as machine-readable accounting and governance objects — the resource system can receive and originate economic events and carry adaptive governance rules, not merely be described analytically. + +### 1.3 Scope + +A **Source-NDO** is a Nondominium Object whose Layer 0 `NondominiumIdentity` represents a **generative ecological system** (watershed, river, forest, fishery, wetland, atmosphere, soil system) or a **generative knowledge commons** (open-source design repository, scientific knowledge base, language corpus — sources that produce non-rival resources). See §2.3 for the full type taxonomy. + +Source-NDO is a **post-MVP** extension. It does not require breaking changes to existing entry types; it adds new typed Layer 0 attributes, a new `vf:Source` role for ValueFlows events, and an adaptive governance pattern built on the existing governance-as-operator architecture. + +--- + +## 2. Conceptual Model + +### 2.1 Three ontological categories + +``` +AGENT — acts, intends, commits, bears responsibility + — individuals, organisations, networks, bots + +RESOURCE — appropriable, inventoriable output + — water in a tank, fish landed, timber cut, a tool in custody + +SOURCE — generative system that yields Resources, receives effects, + — conditions future possibilities, regenerates or degrades + — not owned, not an agent, not merely a stock behind a flow +``` + +A Source **yields** Resources (a river yields cubic metres of water when abstracted). A Source **receives** ecological effects (a river receives heavy-metal discharge). A Source **conditions** other Sources (a forest conditions river infiltration and flow stability). These are distinct event types, all of which become first-class economic events once the `Source` primitive is available as a flow endpoint. + +### 2.2 Source as NDO + +In the Nondominium architecture, a Source-NDO is a `NondominiumIdentity` entry with: +- `property_regime: Nondominium` (or `CommonPool` for rivalrous consumable ecological stocks) +- `resource_nature: Physical` or `Information` (see §2.3) +- A set of **Source-specific Layer 0 extension attributes** (§4.1) +- **No `primaryAccountable`** — stewardship relations use `stewardedBy` links to Agent(s) with a stewardship role, never ownership +- **Governance-as-adaptive-operator** (§5): the governance loop is cybernetic rather than rule-evaluation only + +The Layer 0 identity hash becomes the stable anchor for the source's entire economic history — all events that extract from it, discharge into it, or restore it are linked against this hash. + +### 2.3 Source type taxonomy + +| Source type | Examples | ResourceNature equivalent | Notes | +|---|---|---|---| +| **Ecological — hydrological** | Watershed, river, groundwater, wetland | `Physical` | Rivalrous; extraction and pollution compete | +| **Ecological — biological** | Forest, fishery, soil system, biodiversity | `Physical` | Some rivalrous (fishery); some regenerative | +| **Ecological — atmospheric** | Atmosphere, climate system | `Physical` | Assimilation capacity rivalrous | +| **Knowledge commons** | Open-source design repository, scientific commons, language corpus | `Information` | Non-rivalrous; yields knowledge resources | +| **Social commons** | Community, network, trust fabric | `Information` | Non-rivalrous; yields social capital and governance capacity | + +The existing `ResourceNature` enum covers Source types adequately for Layer 0 classification; a separate `SourceType` sub-classification is recommended for Layer 1 (§4.2). + +### 2.4 Source hierarchy and coupling + +Sources can be organised hierarchically and can condition each other. These are **first-class relations** in the Source-NDO model: + +``` +Source → yields → Source (generative parenthood: watershed yields river) +Source → conditions → Source (coupling: forest conditions river flow and resilience) +Source → yields → Resource (production: river yields gallons of water when abstracted) +``` + +Example: + +``` +WATERSHED (complex system — black box) + ├── RIVER (sub-source) ─── yields ──► water m³ (EconomicResource) + ├── FOREST (sub-source) ─── yields ──► timber (EconomicResource) + │ └── conditions RIVER (improved infiltration ↑ river resilience) + ├── FAUNA (sub-source) ─── yields ──► fish (EconomicResource) + └── FLORA (sub-source) ─── yields ──► herbs (EconomicResource) +``` + +The watershed is treated as a **black box**: its full interior is not modelled. Governance operates on observable boundary events, not on a complete internal description. This is the black-box principle (Ashby, 1956; Snowden & Boone, 2007): in complex domains, govern observable periphery and adapt; do not claim to model the interior. + +--- + +## 3. ValueFlows Extension: `vf:Source` + +### 3.1 The extension + +Source-NDO proposes adding `vf:Source` as a typed role for flow endpoints in ValueFlows economic events, alongside `Agent` and `EconomicResource`. The single new affordance: **flows may originate from and terminate in Sources, not only in Agents or Resources**. + +### 3.2 Event types using Sources as flow endpoints + +**Extraction (Source as provider):** +``` +EconomicEvent { + action: extract, + provider: River(Source), + receiver: AgriCoop(Agent), + quantity: 10000 m³ water +} +→ decrements River.currentStock; depletion is visible +``` + +**Non-consumptive use (Source as provider of flux, not stock):** +``` +EconomicEvent { + action: use, + provider: River(Source), + receiver: HydroDam(Agent), + effect: River.regimeState (altered timing/sediment, not volume) +} +``` + +**Pollution / loading (Source as receiver):** +``` +EconomicEvent { + action: produce, + provider: MiningCo(Agent), + receiver: River(Source), + quantity: 50 kg heavy metals +} +→ debits River.assimilationCapacity; pollution is visible +``` + +**Regeneration (Agent raises a Source):** +``` +EconomicEvent { + action: raise, + target: Forest(Source), + provider: RegenCollective(Agent), + quantity: 1000 trees +} +→ Forest.conditions(River): improved infiltration raises River.fluxRate and resilience +``` + +### 3.3 What the extension removes + +Adding `vf:Source` eliminates: + +| Fiction removed | Description | +|---|---| +| **False ownership claim** | No `primaryAccountable` needed; no fictional steward-as-owner | +| **Resource-from-nowhere `raise`** | Extraction from a Source is debited against it; depletion is visible | +| **Resource/Agent dual-typing** | Sources can receive pollution events without being attributed agency | +| **Inexpressible source hierarchy** | `Source yields Source` is a native edge | +| **Inexpressible cross-source coupling** | `Source conditions Source` is a native edge | +| **Missing black-box epistemics** | `complexInterior: true` and `regimeState` encode partial knowability | +| **Missing governance reflexivity** | Events accumulate on the Source → rules adapt → future events are conditioned | + +--- + +## 4. Data Model + +### 4.1 Source-specific Layer 0 attributes (extension to `NondominiumIdentity`) + +These attributes extend the existing `NondominiumIdentity` for Source-NDOs. They may be implemented as a separate `SourceProfile` entry linked to Layer 0 (to avoid breaking changes) or as additional optional fields on `NondominiumIdentity` guarded by `resource_nature`. + +```rust +pub struct SourceProfile { + pub ndo_identity_hash: ActionHash, // links to NondominiumIdentity + + // Ecological condition state (updated by governance events) + pub current_stock: Option, // current extractable quantity + pub flux_rate: Option, // natural replenishment rate per period + pub assimilation_capacity: Option, // pollution absorption capacity remaining + pub regime_state: SourceRegimeState, // ecological regime classification + pub resilience: Option, // 0.0–1.0 resilience index + pub tipping_threshold: Option, // stock/flux ratio below which regime shift is likely + + // Complexity economics dimensions + pub adaptive_capacity: Option, // ability to discover new viable configurations + pub generative_capacity: Option, // capacity to produce future resources and opportunities + pub dependency_index: Option, // proportion of network agents dependent on this source + + // Coupling relations (links, not inline fields) + pub source_type: SourceType, // Hydrological | Biological | Atmospheric | Knowledge | Social + pub complex_interior: bool, // always true for ecological sources; governs black-box stance + + // Stewardship (replaces primaryAccountable) + pub stewarded_by: Vec, // agents with stewardship obligations (not ownership) + + pub created_at: Timestamp, + pub last_condition_update: Timestamp, +} + +pub enum SourceRegimeState { + Pristine, // minimal anthropogenic impact; high resilience + Stable, // functioning within normal variability; monitoring adequate + Stressed, // measurable degradation; precautionary governance active + Degraded, // significant loss of function; restoration required + Critical, // near tipping threshold; emergency governance possible + Transformed, // post-regime-shift; new stable state (may be lower function) +} + +pub enum SourceType { + Hydrological, // watershed, river, groundwater, wetland + Biological, // forest, fishery, soil system, biodiversity + Atmospheric, // atmosphere, climate system + KnowledgeCommons, // open-source repository, scientific commons + SocialCommons, // community, trust fabric +} +``` + +### 4.2 Ecological value vector (Layer 1 — informative) + +The ecological value of a Source is multidimensional and cannot be collapsed into one metric (aligned with IPBES Values Assessment and OVN value theory). At Layer 1, the `SourceSpecification` should support expressing: + +| Dimension | Description | Example metrics | +|---|---|---| +| **Sustenance** | Ongoing provision of economic resources | Water availability, biomass, fish population, pollination rates | +| **Regeneration** | Capacity to restore itself and other sources | Soil formation rate, carbon sequestration, water quality recovery | +| **Resilience** | Stabilisation of the broader socio-ecological system | Biodiversity index, redundancy, shock response | +| **Adaptive capacity** | Ability to evolve into new viable configurations | Genetic diversity, habitat diversity, innovation potential | +| **Generative capacity** | Capacity to produce future resources and opportunities not yet known | Ecosystem complexity, connectivity, carrying capacity | +| **Commons value** | Significance as shared infrastructure across the agent network | Number and diversity of dependent agents, dependency ratio | +| **Learning value** | Knowledge generated through observation and interaction | Monitoring outputs, governance improvements, model accuracy | + +### 4.3 Source-to-Source links + +```rust +pub enum SourceLinkType { + Yields, // Source yields a sub-Source (watershed → river) + Conditions, // Source conditions another Source (forest → river flow) + ProvidedBy, // inverse of Yields (river is provided by watershed) +} + +pub struct SourceCouplingLink { + pub from_source_hash: ActionHash, + pub to_source_hash: ActionHash, + pub link_type: SourceLinkType, + pub coupling_strength: Option, // 0.0–1.0; estimated from monitoring data + pub notes: Option, +} +``` + +--- + +## 5. Governance Requirements + +### 5.1 Adaptive governance loop + +Source-NDO governance operates as a **cybernetic loop** rather than a one-time rule evaluation. This extends the governance-as-operator pattern to complex, partially unknowable ecological systems: + +``` +Boundary events (extraction, discharge, restoration) + ↓ +Event ledger (accumulated on Source Layer 0 hash) + ↓ +Ecological interpretation (by scientists, local stewards, monitoring systems) + ↓ +Governance rule adaptation (GovernanceRule entries updated or replaced) + ↓ +Access affordances (who can do what, under what conditions, up to what quantity) + ↓ +Conditioned future events (agents interact with the Source under new rules) + ↓ (loop) +``` + +The **black-box principle** governs this loop: stewards do not need to model the full interior of the watershed. They observe peripheral signals (withdrawals, pollutant loads, sensor readings, fish counts, flood events, seasonal variation, local knowledge). Governance adapts from these signals. As the source ledger grows, stewards can revise thresholds, add monitoring obligations, change access rules, or introduce graduated sanctions. + +This is "beyond Ostrom" in the complexity-science sense: Ostrom's design principles assume a *complicated* resource system whose rules can be designed from adequate knowledge. Sources are *complex* systems with nonlinear dynamics and potential regime shifts. Rules must adapt continuously as the source ledger grows (Holling, 1973; Gunderson & Holling, 2002; Folke et al., 2005). + +### 5.2 PropertyRegime constraints + +Source-NDOs SHALL observe the following property regime constraints: + +- **MUST be `Nondominium` or `CommonPool`**: `Private`, `Commons`, `Pool`, and `Collective` regimes are inappropriate for ecological sources — they imply ownership or enclosure that the Source primitive is designed to prevent. +- `PropertyRegime::Nondominium` is preferred: governance-embedded uncapturability, no `primaryAccountable`. +- `PropertyRegime::CommonPool` may apply to rivalrous consumable stock sources (e.g., a specific fish stock where the extraction quota is the primary governance mechanism). + +### 5.3 Governance rule requirements (REQ-SOURCE-GOV-*) + +**REQ-SOURCE-GOV-01**: Source-NDO governance MUST support **adaptive rule revision**: governance rules attached to a Source should be updatable through a defined governance process (not only by the initiator), reflecting changes in ecological interpretation. Rule version history SHALL be maintained. + +**REQ-SOURCE-GOV-02**: Source-NDOs MUST support **access affordance rules** expressed as quantitative constraints on boundary events: maximum extraction quantity per period, maximum pollutant loading, minimum restoration obligation per extraction event, seasonal restrictions. + +**REQ-SOURCE-GOV-03**: The governance evaluation for Source-NDO events MUST check current `SourceRegimeState`. Events that would push the source toward or past `tipping_threshold` MAY be blocked or require multi-validator approval under precautionary governance rules. + +**REQ-SOURCE-GOV-04**: Source-NDOs SHOULD support **monitoring obligations** as a class of `GovernanceRule`: agents that extract from or discharge into a Source may be required to submit condition data as a precondition for continued access. Monitoring data updates `SourceProfile.regime_state` and related indicators. + +**REQ-SOURCE-GOV-05**: `SourceRegimeState` transitions (e.g. `Stable → Stressed`, `Stressed → Degraded`) MUST be governance-validated — they require evidence (monitoring data, scientific assessment, community observation) and multi-validator approval, not unilateral declaration. + +**REQ-SOURCE-GOV-06**: The governance module SHALL record all Source-NDO boundary events as `EconomicEvent` entries linked to the Source's Layer 0 hash, forming an auditable ledger of all extraction, loading, non-consumptive use, and restoration actions. + +### 5.4 Stewardship model + +Source-NDOs use **stewardship** rather than ownership: + +| Concept | Standard NDO | Source-NDO | +|---|---|---| +| Custodian | `EconomicResource.custodian: AgentPubKey` | Not applicable (Sources are not held in custody) | +| Primary responsible | `primaryAccountable: AgentPubKey` | `stewardedBy: Vec` — obligations, not rights | +| Role type | `PrimaryAccountableAgent` | `Steward` — a new functional role for Source governance | +| Transfer | Custody transfer event | Stewardship succession event (governance-validated) | + +The `Steward` role carries **obligations** (monitoring, maintaining condition indicators, processing access requests, implementing governance decisions) without conferring **alienation rights**. No steward can privatise a Source-NDO. + +### 5.5 Data sovereignty and knowledge integration + +**REQ-SOURCE-GOV-07**: Source-NDOs MUST support attaching **qualitative and community-validated condition signals** to the event ledger, not only quantitative sensor data. Narrative observations, indigenous knowledge assessments, and community-validated condition reports are legitimate inputs to governance interpretation. + +**REQ-SOURCE-GOV-08**: Sensitive ecological data (endangered species locations, sacred sites, private land-use details) attached to Source-NDO records SHALL be stored as Holochain private entries with capability-grant access control, following the `PrivatePersonData` model in `zome_person`. The PPR system's privacy model applies to stewardship participation data. + +--- + +## 6. Lifecycle and Layer Activation + +### 6.1 LifecycleStage for Source-NDOs + +Source-NDOs use the same `LifecycleStage` enum as other NDOs, but the semantic mapping differs: + +| LifecycleStage | Source-NDO meaning | +|---|---| +| `Ideation` | Source identified and named; Layer 0 only; minimal condition data | +| `Specification` | Boundary conditions defined; stakeholders identified; monitoring plan drafted | +| `Development` | Active monitoring established; governance rules being developed; stewards named | +| `Stable` | Governance rules active; monitoring operational; event ledger accumulating | +| `Active` | Full governance loop operational; regular rule revision cycle in place | +| `Hibernating` | Governance temporarily paused (e.g. seasonal closure, dispute resolution in progress) | +| `Deprecated` | Source governance superseded by a broader governance structure (e.g. a watershed-level Source-NDO supersedes a river-level one) | +| `EndOfLife` | Irreversible loss (e.g. geological change, complete ecosystem collapse); Layer 0 tombstone preserved as historical record | + +### 6.2 Layer activation + +Source-NDOs use the same three-layer model as all NDOs: + +- **Layer 0**: `NondominiumIdentity` + `SourceProfile` extension; permanent anchor +- **Layer 1**: `SourceSpecification` — boundary definitions, monitoring framework, stakeholder map, ecological value vector expression; activated when governance framework is being formalised +- **Layer 2**: Economic events, commitments, claims, PPRs; activated when boundary events begin to be recorded + +--- + +## 7. PPR Integration + +Private Participation Receipts for Source-NDO interactions use the existing 16-category system with the following emphasis: + +| PPR category | Source-NDO use | +|---|---| +| `ValidationActivity` | Monitoring data submission, condition assessment, governance interpretation | +| `RuleCompliance` | Compliance with extraction quotas, discharge limits, monitoring obligations | +| `MaintenanceCommitmentAccepted` / `MaintenanceFulfillmentCompleted` | Restoration commitments (reforestation, riparian restoration, remediation) | +| `DisputeResolutionParticipation` | Disputes about Source condition assessments or access affordances | +| `ResourceCreation` | Registration of a new Source-NDO and initial condition assessment | +| `GoodnFaithTransfer` | Stewardship succession — transfer of steward obligations to a new agent | + +Stewardship participation records (monitoring contributions, governance interpretation events, restoration work) SHALL be PPR-eligible, enabling stewards to accumulate governance standing through contribution to Source health. + +--- + +## 8. Requirements Summary (REQ-SOURCE-*) + +### 8.1 Ontological requirements + +**REQ-SOURCE-ONT-01**: The system SHALL recognise `Source` as a distinct ontological category for flow endpoints in economic events, separable from both `Agent` and `EconomicResource` (cf. `vf:Source` ValueFlows extension, §3). + +**REQ-SOURCE-ONT-02**: Source-NDOs SHALL NOT require a `primaryAccountable` agent. The property regime SHALL be `Nondominium` or `CommonPool`. Governance SHALL reject any `GovernanceRule` that attempts to assign ownership of a Source-NDO. + +**REQ-SOURCE-ONT-03**: The system SHALL support Source-to-Source links of types `yields`, `conditions`, and `providedBy` (§4.3) to represent source hierarchies and ecological coupling. + +**REQ-SOURCE-ONT-04**: Source-NDOs SHALL be represented on the DHT as `NondominiumIdentity` entries with a linked `SourceProfile` extension, using the permanent Layer 0 hash as the event ledger anchor. + +### 8.2 Data model requirements + +**REQ-SOURCE-DATA-01**: `SourceProfile` SHALL record: `current_stock`, `flux_rate`, `assimilation_capacity`, `regime_state`, `resilience`, `tipping_threshold`, `adaptive_capacity`, `generative_capacity`, `dependency_index`, `source_type`, `complex_interior`, `stewarded_by` (§4.1). + +**REQ-SOURCE-DATA-02**: `SourceRegimeState` SHALL progress through: `Pristine → Stable → Stressed → Degraded → Critical → Transformed`, with governance-validated transitions in both directions (§5.3, REQ-SOURCE-GOV-05). + +**REQ-SOURCE-DATA-03**: The Layer 1 `SourceSpecification` SHOULD support the ecological value vector dimensions: Sustenance, Regeneration, Resilience, Adaptive Capacity, Generative Capacity, Commons Value, Learning Value (§4.2). + +### 8.3 Event and governance requirements + +See §5.3 (REQ-SOURCE-GOV-01 through REQ-SOURCE-GOV-08) for the full governance requirement set. + +**REQ-SOURCE-EVENT-01**: Boundary events on Source-NDOs (extraction, loading, non-consumptive use, regeneration) SHALL be recorded as `EconomicEvent` entries with the Source's Layer 0 hash as the `resource_inventoried_as` target, regardless of whether the Source is provider or receiver. + +**REQ-SOURCE-EVENT-02**: Extraction events from a Source SHALL decrement `SourceProfile.current_stock` (or its `flux_rate`-denominated period budget); loading events SHALL decrement `assimilation_capacity`. These updates SHALL be governance-validated, not directly writable by the extracting/discharging agent. + +**REQ-SOURCE-EVENT-03**: Regeneration events (restoration, remediation) SHALL be able to increment `current_stock`, `flux_rate`, `assimilation_capacity`, or `resilience` through governance-validated `raise`-equivalent events, recording the contributing agent and PPR. + +--- + +## 9. Implementation Phasing (informative) + +| Phase | Deliverable | +|---|---| +| **Phase A** | `SourceProfile` entry type; `SourceType` and `SourceRegimeState` enums; Layer 0 + SourceProfile link; Source-to-Source coupling links; `Steward` role type | +| **Phase B** | `vf:Source` event role; boundary event recording (extraction, loading, regeneration); event-triggered `current_stock` and `assimilation_capacity` updates | +| **Phase C** | Adaptive governance loop: `SourceRegimeState` transitions; access affordance rules; monitoring obligation `GovernanceRule` type; precautionary blocking at `tipping_threshold` | +| **Phase D** | Ecological value vector expression in Layer 1 `SourceSpecification`; PPR integration for stewardship participation; ZKP-compatible proof of monitoring obligation fulfilment | +| **Phase E** | Cross-DNA source hierarchy links (watershed-level Source-NDO governing river-level Source-NDOs across different communities); federation-level source governance | + +--- + +## 10. Relation to Complexity Oriented Programming + +Source-NDO is a direct application of COP principles (see `complexity-oriented-programming` skill): + +| COP principle | Source-NDO enactment | +|---|---| +| **Dynamic complexity matching** | Governance overhead grows from Layer 0 (Ideation, minimal) to full adaptive loop (Active); the system never requires complete ecological specification upfront | +| **Stigmergic coordination** | Source-NDOs modify the governance environment via their ledger: stewards respond to source condition signals rather than following explicit orders | +| **Anti-fragility** | The adaptive governance loop treats ecological stress events as information for rule revision, not as failures; the system gets better at governance as the ledger grows | +| **Path-dependency awareness** | `SourceRegimeState` history and event ledger preserve the full trajectory; governance rules carry their provenance | +| **Fractal composability** | Source hierarchies (watershed → river → water) use the same NDO primitives at every scale; governance principles are self-similar | +| **Probe-sense-respond** | The governance loop is explicitly cybernetic: boundary events probe; condition monitoring senses; governance rule adaptation responds | + +--- + +## 11. Traceability + +| Source | Normative IDs | +|---|---| +| `source-ndo-paper.md` §8 (Implementation) | REQ-SOURCE-ONT-01 – -04 | +| `source-ndo-paper.md` §4 (Black-box principle) | REQ-SOURCE-GOV-01, -03, -04 | +| `source-ndo-paper.md` §6 (Governance loop) | REQ-SOURCE-GOV-02, -06, REQ-SOURCE-EVENT-01 – -03 | +| Ostrom SES framework | REQ-SOURCE-ONT-01 (resource system = Source) | +| `ndo_prima_materia.md` §4 (three-layer model) | §6 (Layer activation) | +| `ndo_prima_materia.md` governance-as-operator | §5.1 (adaptive governance loop) | +| `resources.md` §4.4.3 (property regimes) | REQ-SOURCE-ONT-02 | +| `governance.md` §2.1 (governance-as-operator) | §5.1 | + +--- + +*This is a normative post-MVP requirements document. Source-NDO does not modify existing REQ-NDO-* invariants (Layer 0 permanence, governance-as-operator, PPR privacy model). It extends the economic ontology at the flow-endpoint level and adds Source-specific governance patterns on top of the existing architecture.* diff --git a/documentation/requirements/requirements.md b/documentation/requirements/requirements.md index 2f26085..e46cbf9 100644 --- a/documentation/requirements/requirements.md +++ b/documentation/requirements/requirements.md @@ -50,6 +50,7 @@ Optional, pay-as-you-grow integrations (communities may adopt one, both, or neit | **Lobby DNA** | Multi-network federation: entry point (Lobby DHT) + per-group coordination (Group DHT) + NDO-to-NDO hard links, Contributions, Smart Agreements; dual deployment (standalone + Moss applet) | REQ-LOBBY-*, REQ-GROUP-*, REQ-NDO-EXT-* | [lobby-dna.md](post-mvp/lobby-dna.md) / [lobby-architecture.md](../specifications/post-mvp/lobby-architecture.md) | | **Unyt** | Economic settlement (Smart Agreements, RAVE proofs, PPR↔RAVE provenance) | `ndo_prima_materia.md` §6.6, §11.5; REQ-NDO-CS-07–CS-11 | [unyt-integration.md](post-mvp/unyt-integration.md) | | **Flowsta** | Cross-app identity (Vault `IsSamePersonEntry`, `FlowstaIdentity` slot, DID, recovery); Tier 1 (Phase 1) vs Tier 2 (Phase 3) | `ndo_prima_materia.md` §6.5–6.7, §11.6; REQ-NDO-CS-12–CS-15; REQ-NDO-AGENT-07–08 | [flowsta-integration.md](post-mvp/flowsta-integration.md) | +| **Source-NDO** | `Source` as a third ontological primitive (neither Agent nor Resource): generative ecological systems (watersheds, rivers, forests, fisheries) and knowledge commons. Yields Resources, receives ecological effects, conditions future possibilities. Requires `vf:Source` ValueFlows extension, `SourceProfile` Layer 0 extension, `stewardedBy` stewardship model, and adaptive cybernetic governance loop. | REQ-SOURCE-ONT-*, REQ-SOURCE-GOV-*, REQ-SOURCE-DATA-*, REQ-SOURCE-EVENT-* | [source-ndo-requirements.md](post-mvp/source-ndo-requirements.md) / [source-ndo-paper.md](post-mvp/source-ndo-paper.md) | **Knowledge-base context** (ontology, OVN alignment, gap analysis): [resources.md](../archives/resources.md), [agent.md](../archives/agent.md), [governance.md](../archives/governance.md). This PRD remains the anchor for MVP user stories and REQ-USER / REQ-RES / REQ-GOV IDs; NDO-wide REQ-NDO-* IDs are defined in `ndo_prima_materia.md` §9. diff --git a/documentation/requirements/resources.md b/documentation/requirements/resources.md index 0e81ba9..5a70289 100644 --- a/documentation/requirements/resources.md +++ b/documentation/requirements/resources.md @@ -71,6 +71,24 @@ In complexity economics terms: these intangibles are the *emergent properties* o The NDO does not need to *track* intangible resources in the same way it tracks a bicycle or a CAD file. But it must be *aware* of them — as a category of resource type — to avoid designing governance mechanisms that damage them. +### 1.6 Source: the Third Category + +The REA ontology that underpins ValueFlows operates with two primitives: **Agent** and **Resource**. The resource classification work in sections 1.1–1.5 implicitly accepts this duality. But 15 years of OVN practice and a growing literature on socio-ecological systems accounting reveal a case where neither primitive is adequate: *generative ecological systems* — watersheds, rivers, forests, fisheries, atmospheric assimilation capacity — that yield resources, receive ecological effects, and condition future possibilities without being ownable, intentional, or inventoriable in the standard sense. + +The academic paper [`source-ndo-paper.md`](post-mvp/source-ndo-paper.md) demonstrates with Occam's razor that modelling a watershed under `Nondominium` governance without a `Source` primitive requires three active ontological fictions and leaves four economic relations inexpressible. Adding one new primitive removes all seven distortions. + +**`Source` is a third ontological category**: a generative, non-ownable, partially unknowable system that: +- **yields** Resources (a river yields cubic metres of water when abstracted) +- **receives** ecological effects (a river receives heavy-metal discharge) +- **conditions** other Sources (a forest conditions river flow and resilience) +- **accumulates** a historical ledger of boundary events for adaptive governance + +Sources are represented in the Nondominium architecture as **Source-NDOs**: `NondominiumIdentity` entries with `PropertyRegime::Nondominium` (or `CommonPool`), a linked `SourceProfile` extension for condition indicators, and a `stewardedBy` relation instead of `primaryAccountable`. No agent owns a Source; stewards carry obligations to maintain the event ledger and adapt governance rules as the source ledger grows. + +This is the cybernetic governance loop: boundary events accumulate → stewards interpret conditions → governance rules adapt → access affordances change → future events are conditioned. It extends the governance-as-operator pattern from complicated (rule-evaluable) to complex (adaptive, signal-based) governance contexts. + +Normative requirements for Source-NDO are in [`source-ndo-requirements.md`](post-mvp/source-ndo-requirements.md). This subsection is an ontological framing note; the detailed data model, governance patterns, and ValueFlows extension (`vf:Source`) are in that document. + --- ## 2. Current Implementation (MVP) @@ -706,6 +724,7 @@ These represent the forward agenda for the generic NDO design: | **Cross-app identity verification** | No mechanism for an agent to prove they are the same person across multiple Holochain apps or external systems. PPR reputation is local to this DHT; no cross-network trust signal | Add `FlowstaIdentity` CapabilitySlot on `Person` hash (`ndo_prima_materia.md` Section 6.7, REQ-NDO-CS-12). Governance rules can require Tier 2–validated Flowsta linking for high-value access (REQ-NDO-CS-14, Flowsta Phase 3). Flowsta DID provides the cross-app identity anchor for portable credentials (REQ-NDO-AGENT-08) | | **Collective agent custodianship** | `EconomicResource.custodian` is currently `AgentPubKey`, assuming individual agent. Collective, Project, Network, and Bot agents (G1) should also be valid custodians | Replace `AgentPubKey` with `AgentContext` (union type) across `EconomicResource.custodian`, `TransitionContext.target_custodian`, and `NondominiumIdentity.initiator` (ref G1, REQ-AGENT-02) | | **Intangibles** | Social capital, trust, competencies — not tracked but should be preserved | Design principle: NDO governance architecture should cultivate intangibles as emergent properties, not track them as entries | +| **Source as ontological primitive** | Generative ecological systems (watersheds, fisheries, forests) and knowledge commons fit neither `Agent` nor `Resource` faithfully. Modelling them as resources requires false `primaryAccountable` ownership; omitting them leaves depletion and ecological loading invisible | Introduce `Source` as a typed NDO specialization: `SourceProfile` entry linked to Layer 0, `stewardedBy` relation replacing custodian, `vf:Source` ValueFlows extension for flow endpoints. See [`source-ndo-requirements.md`](post-mvp/source-ndo-requirements.md) | --- @@ -863,6 +882,8 @@ These defaults are starting points — communities override them through the Gov **Intangibles** matter negatively — as a design constraint. The OVN wiki's extensive treatment of intangibles is a warning: governance systems that ignore social capital, trust, and community sense will inadvertently destroy them through surveillance, commodification, or capture. The NDO's design choices (peer validation rather than central authority, private PPRs rather than public scoring, permissionless access rather than gatekeeping) are intangible-preserving choices. They should be recognised as such, so that future design decisions are evaluated against the same standard. +**Source as third ontological category** matters because omitting it makes ecological commons invisible to the economic ledger. Without `Source`, depletion events appear as `raise` (resource-from-nowhere), ecological loading disappears entirely, and the false fiction of an owning agent must be maintained for every watershed and fishery under `Nondominium` governance. The governance-as-operator architecture is exactly suited to Source-NDOs: the event ledger accumulates boundary signals, stewards interpret them, governance rules adapt, and future access is conditioned by source health — a cybernetic loop that implements adaptive governance for complex ecological systems. This matters because the single most important use case for the `Nondominium` property regime in natural commons is ecological: fisheries, watersheds, forests. A governance system that cannot model these without distortion is unsuitable for the most important commons of all. + --- *This is a living document. As the generic NDO project begins, the gap analysis in Section 5.3 should be converted into formal requirements. The forward map in Section 6 should be reviewed against the actual NDO project scope and prioritised accordingly. The OVN wiki at [ovn.world](https://ovn.world) remains the authoritative reference for community-validated resource ontology concepts.* diff --git a/documentation/zomes/resource_zome.md b/documentation/zomes/resource_zome.md index d355af4..8116ac9 100644 --- a/documentation/zomes/resource_zome.md +++ b/documentation/zomes/resource_zome.md @@ -11,6 +11,8 @@ The Resource zome implements the core resource management infrastructure for the > - `CapabilitySlot` — Layer 0 identity hash to capability targets (stigmergic attachment surface) > > **Unyt (post-MVP):** endorsed economic terms use typed **`EconomicAgreement`** `GovernanceRule` data (`ndo_prima_materia.md` §6.6, REQ-NDO-CS-09–CS-11; `documentation/requirements/post-mvp/unyt-integration.md`). +> +> **Source-NDO (post-MVP):** `NondominiumIdentity` may represent generative ecological systems (watersheds, rivers, fisheries) as **Source-NDOs** — a typed NDO specialization that uses `PropertyRegime::Nondominium` or `CommonPool`, adds a linked `SourceProfile` entry (condition indicators, `stewarded_by`, `regime_state`, etc.), and extends the governance-as-operator pattern with an adaptive cybernetic loop. Source-NDOs require the `vf:Source` ValueFlows extension for flow endpoints (see `documentation/requirements/post-mvp/source-ndo-requirements.md` and `documentation/hREA/valueflows-1.0-compliance.md §P3-1`). No breaking changes to existing `NondominiumIdentity` fields are required; `SourceProfile` is a separate linked entry. ## Core Data Structures diff --git a/pai/human_ai_collaboration.md b/pai/human_ai_collaboration.md new file mode 100644 index 0000000..4860bd8 --- /dev/null +++ b/pai/human_ai_collaboration.md @@ -0,0 +1,677 @@ + + +# AI "cognition" +Below is a **technical, evidence-based analysis** of current AI agent capabilities relevant to **cognitive offloading**, what specific tasks humans can offload to AI today, and how these capabilities shape what gets delegated vs. what remains human-centric. + +## 1. Core AI Capabilities (Functional Breakdown) + +Modern AI systems exhibit a set of discrete capabilities that can be classified systematically. These are grounded in observed system performance and use-case deployment. + +### A. **Perception & Pattern Recognition** + +These are tasks that map raw signals to structured interpretations with high reliability. + +* **Natural language processing (NLP):** parsing text, extracting entities, summarization, translation, dialogue generation (e.g., large language models). +* **Vision systems:** object detection, classification, segmentation in images/video. +* **Signal classification:** audio recognition, speech-to-text, sensor data interpretation. + +This category offloads the *sensory decoding and pattern extraction* that humans do through perception. The outputs are explicit symbolic or latent representations that humans use for further reasoning. ([McKinsey & Company][1]) + +*Inference:* Perception tasks remove the need for humans to read/interpret raw data streams; instead, humans focus on interpretation of symbolic outputs. + +--- + +### B. **Data Retrieval, Aggregation, and Summarization** + +AI excels at searching, filtering, and synthesizing information across large corpora. + +* **Search and retrieval:** indexing and recall from massive datasets +* **Summarization / abstraction:** compressing information to key points +* **Comparative synthesis:** identifying patterns across sources + +This offloads **memory and search demands** from human working memory and long-term storage. Users no longer need to remember details; the AI retrieves and presents relevant information on demand, effectively acting as *externalized working memory*. ([MDPI][2]) + +--- + +### C. **Structured Decision Support** + +AI can estimate likely outcomes, recommend actions, or optimize decisions under constraints. + +* **Predictive modelling:** forecasting based on historical data +* **Optimization:** scheduling, resource allocation, portfolio balancing +* **Scenario evaluation:** cost/benefit analyses + +These capabilities are not yet *true autonomous reasoning* in the human sense, but they provide **quantitative decision inputs** based on learned correlations and patterns. + +*Example:* AI planners can optimize schedules or workflows that humans previously optimized manually. + +--- + +### D. **Multi-Step Task Automation (AI Agents)** + +Recent designs embed AI into agents that can interact with other tools and software. + +* Agents execute sequences of actions (e.g., calendar management, online procurement, research workflows). +* They interface with virtual environments to *operate* software on a user’s behalf. ([The Verge][3]) + +This is a **weak form of autonomous agency** — capable of procedural task execution — but still supervised and constrained by user instructions and safety checks. + +--- + +### E. **Emerging Reasoning and Abstraction** + +AI systems show gradual improvement in tasks requiring reasoning-like behaviors: + +* **Probabilistic inference** +* **Contextual understanding through large-scale embeddings** +* Some logical composition via neurosymbolic hybrid models (integrating neural nets with symbolic reasoning). ([Wikipedia][4]) + +However, tasks requiring **deep semantic abstraction, novel analogy creation, and open-ended conceptual innovation** remain outside reliable performance for general contexts. ([arXiv][5]) + +--- + +## 2. Cognitive Tasks Currently Offloaded to AI + +We can identify high-level categories where humans are currently **delegating cognitive work**: + +### 2.1. **External Memory and Search** + +Humans no longer memorize facts; instead, rely on AI to fetch, rank, and contextualize information. + +* Delegated tasks: memory recall, search inference, document retrieval +* Cognitive effect: reduced working memory burden; potential for long-term memory atrophy if not balanced. ([MDPI][2]) + +--- + +### 2.2. **Routine Procedural Reasoning** + +Tasks that follow structured rules or well-defined procedures are efficiently outsourced: + +* Planning and scheduling +* Report generation +* Routine communications (emails, summaries) + +These reduce **low-level decision load**, freeing human attention for strategic oversight. + +--- + +### 2.3. **Pattern Detection and Interpretation** + +Humans currently offload pattern recognition tasks: + +* Detecting anomalies +* Parsing data +* Tagging and classification + +This allows humans to focus on higher-order interpretation rather than raw extraction. + +--- + +### 2.4. **Predictive Analytics** + +Humans use AI to estimate future trends: + +* Forecasting demand +* Risk scoring +* Predictive recommendations + +This shifts cognitive effort from “calculating outcomes” to “interpreting model outputs.” + +--- + +### 2.5. **Automation of Multi-Step Workflows** + +AI agents now perform linked task sequences: + +* Booking, planning, preparation workflows +* Cross-platform interactions + +This represents delegation of procedural logic and task orchestration, not yet conceptual creativity. + +--- + +## 3 Cognitive Profiles: What Tasks Remain Human-Intensive + +Based on current capabilities, tasks that **remain anchored in human cognition**: + +### A. **Deep Abstraction & Creative Innovation** + +AI lacks robust generalization beyond its training contexts and few-shot creativity that arises from internal conceptual schemas. ([arXiv][5]) + +--- + +### B. **Judgment Under Uncertainty** + +Human judgment integrates tacit knowledge, ethical reasoning, and context — areas where AI remains weak or opaque. + +--- + +### C. **Complex Social Reasoning** + +Human emotional intelligence, empathy, moral nuance, and norms understanding are not reliably encoded in current AI models. + +--- + +### D. **Meta-Reasoning and Self-Reflection** + +Humans monitor their own thinking, update norms, and generate new abstract frameworks — distinct from pattern learning. + +--- + +## 4 Cognitive Offloading and Human Skill Dynamics + +From cognitive science research: + +* **Cognitive offloading** to external tools reduces working memory load and allows humans to attend to complex tasks. ([MDPI][2]) +* However, **excessive reliance** can lead to atrophy in critical thinking, problem-solving, and memory retention if not balanced deliberately. ([MDPI][2]) + +This suggests a **trade-off landscape**: + +* Short-term efficiency gains vs. +* Long-term development of cognitive resilience and complex reasoning. + +--- + +## 5 Summary: AI Capabilities for Cognitive Offload + +CPU-like breakdown of capabilities: + +| Category | Offload Domain | Human Cognitive Frequency Reduced | +| ----------------------- | ---------------------------------------- | --------------------------------- | +| Perception | sensory decoding (text, images, signals) | high | +| Memory | search & recall | high | +| Routine logic | procedural workflows | high | +| Pattern analytics | large data interpretation | moderate | +| Predictive reasoning | forecast & optimization | moderate | +| Abstraction | none reliable | low | +| Social/ethical judgment | none reliable | low | + +--- + +[1]: https://www.mckinsey.com/pt/our-insights/explainers/o-que-e-a-ia?utm_source=chatgpt.com "O que é a IA (Inteligência Artificial)? | McKinsey" +[2]: https://www.mdpi.com/2075-4698/15/1/6?utm_source=chatgpt.com "AI Tools in Society: Impacts on Cognitive Offloading and the Future of Critical Thinking" +[3]: https://www.theverge.com/ai-artificial-intelligence/709158/openai-new-release-chatgpt-agent-operator-deep-research?utm_source=chatgpt.com "OpenAI's new ChatGPT Agent can control an entire computer and do tasks for you" +[4]: https://pt.wikipedia.org/wiki/IA_neurossimb%C3%B3lica?utm_source=chatgpt.com "IA neurossimbólica" +[5]: https://arxiv.org/abs/2102.10717?utm_source=chatgpt.com "Abstraction and Analogy-Making in Artificial Intelligence" + + + +# What Is Human Cognition? + +A deep survey of major reviews and theoretical syntheses across psychology, neuroscience, social cognition, evolutionary cognition, affective science, and executive function research reveals that **human cognition is not a single system but a layered architecture of interacting processes**. These processes span: + +* Perception and embodied simulation +* Memory systems +* Attention and control networks +* Executive regulation and metacognition +* Decision-making under uncertainty +* Emotion–cognition integration +* Social and cultural cognition +* Abstract reasoning and symbolic processing +* Adaptive and resilience mechanisms +* Developmental and plastic processes + +Across traditions (grounded cognition, executive control models, affective neuroscience, social cognition, evolutionary cognition), the evidence converges: **cognition is integrative, embodied, emotional, predictive, socially embedded, and probabilistic**. + +Below is a structured, exhaustive taxonomy synthesized from major reviews and theoretical frameworks. + +--- + +## Comprehensive Taxonomy of Human Cognitive Capacities + + +### I. Perceptual & Representational Cognition + +**Core Idea:** Cognition begins in perceptual simulation and embodied representation. + +**Key capacities:** + +1. Sensory perception (visual, auditory, somatosensory, olfactory, gustatory) +2. Multisensory integration +3. Pattern recognition +4. Feature detection +5. Object recognition +6. Categorization & classification +7. Concept formation +8. Grounded/embodied simulation +9. Spatial cognition & navigation +10. Temporal perception +11. Predictive coding +12. Perceptual decision-making + +Grounded cognition theory demonstrates that abstract thinking recruits perceptual systems (Barsalou, 2008). Classification research shows categorization is probabilistic rather than rule-bound (Estes, 1994). Decision neuroscience reveals perceptual decisions scale into complex cognition (Shadlen & Kiani, 2013). + +--- + +### II. Attention & Cognitive Control + +**Core Idea:** Cognition requires selective allocation and regulation of mental resources. + +**Key capacities:** + +13. Alerting attention +14. Orienting attention +15. Executive attention +16. Sustained attention +17. Divided attention +18. Selective inhibition +19. Conflict monitoring +20. Task switching +21. Cognitive flexibility +22. Working memory updating + +Attention network models show separable but interacting systems (Posner & Rothbart, 2007). Executive function research emphasizes prefrontal control mechanisms enabling goal-directed cognition (Dalley et al., 2004). + +--- + +### III. Memory Systems + +**Core Idea:** Cognition depends on dynamic storage and reconstruction. + +**Key capacities:** + +23. Working memory +24. Episodic memory +25. Semantic memory +26. Procedural memory +27. Prospective memory +28. Autobiographical memory +29. Associative learning +30. Statistical learning +31. Memory consolidation +32. Reconsolidation +33. Schema integration +34. Mental time travel + +Learning and memory are foundational to classification and reasoning (Estes, 1994). Training studies demonstrate plasticity across memory systems (Lustig et al., 2009). + +--- + +### IV. Executive & Goal-Directed Cognition + +**Core Idea:** Humans regulate behavior through planning and abstraction. + +**Key capacities:** + +35. Planning +36. Strategic reasoning +37. Goal representation +38. Cost–benefit evaluation +39. Delay discounting +40. Impulse control +41. Error monitoring +42. Metacognition (thinking about thinking) +43. Self-regulation +44. Abstract rule formation +45. Hypothesis testing + +Executive function research shows cross-domain control processes (Dalley et al., 2004). Exercise and developmental studies highlight metacognitive growth (Tomporowski et al., 2015). + +--- + +### V. Decision-Making & Cognition Under Uncertainty + +**Core Idea:** Human reasoning is probabilistic and predictive. + +**Key capacities:** + +46. Risk evaluation +47. Ambiguity tolerance +48. Bayesian updating +49. Heuristic processing +50. Evidence accumulation +51. Value integration +52. Confidence estimation +53. Counterfactual reasoning +54. Regret simulation + +Decision neuroscience demonstrates cognition as probabilistic evidence integration (Shadlen & Kiani, 2013). Resilience research shows reappraisal and reinterpretation under uncertainty (Kalisch et al., 2015). + +--- + +### VI. Emotional Cognition & Affective Processing + +**Core Idea:** Emotion is not separate from cognition—it shapes it. + +**Key capacities:** + +55. Emotion perception +56. Emotional appraisal +57. Affective forecasting +58. Mood-congruent processing +59. Reappraisal +60. Emotional memory modulation +61. Empathic resonance +62. Valuation tagging +63. Motivational salience attribution +64. Fear conditioning +65. Reward learning + +Emotion–cognition interaction reviews show dynamic interplay (Hayes et al., 2012). Feelings influence judgment heuristics (Schwarz & Clore, 1996). Neurobiological models link serotonin to emotional and social cognition (Canli & Lesch, 2007). + +--- + +### VII. Social Cognition + +**Core Idea:** Human cognition evolved for group life. + +**Key capacities:** + +66. Theory of Mind +67. Mental state attribution +68. Social categorization +69. Moral reasoning +70. Reputation tracking +71. Coalition reasoning +72. Social norm detection +73. Cooperation strategies +74. Deception detection +75. Social learning +76. Cultural transmission + +Evolutionary models propose cognition scaled with social complexity (Caporael, 1997). Religious cognition may arise as by-products of social-cognitive architecture (Boyer, 2003). + +--- + +### VIII. Language & Symbolic Cognition + +**Core Idea:** Humans manipulate abstract symbolic systems. + +**Key capacities:** + +77. Syntax processing +78. Semantic integration +79. Pragmatic inference +80. Narrative construction +81. Metaphor comprehension +82. Recursive embedding +83. Internal speech +84. Symbol grounding + +Grounded cognition research argues even language recruits sensorimotor systems (Barsalou, 2008). + +--- + +### IX. Creative & Generative Cognition + +**Core Idea:** Humans generate novel representations. + +**Key capacities:** + +85. Divergent thinking +86. Insight generation +87. Conceptual blending +88. Analogical reasoning +89. Problem restructuring +90. Mental simulation +91. Counterfactual imagination +92. Design thinking + +Creativity research shows overlap but partial dissociation from classical cognitive systems (Runco & Chand, 1995). + +--- + +### X. Self & Identity Cognition + +**Core Idea:** Humans model themselves. + +**Key capacities:** + +93. Self-representation +94. Autonoetic consciousness +95. Narrative identity +96. Metacognitive self-evaluation +97. Agency attribution +98. Self–other distinction +99. Future self projection +100. Resilience cognition + +Resilience models emphasize positive reclassification and reinterpretation processes (Kalisch et al., 2015). + +--- + +# Key Theoretical Integrators + +Across the literature: + +* **Cognition is embodied** (Barsalou, 2008) +* **Emotion and cognition are inseparable** (Schwarz & Clore, 1996; Hayes et al., 2012) +* **Executive systems regulate distributed networks** (Dalley et al., 2004) +* **Attention integrates psychological science** (Posner & Rothbart, 2007) +* **Decision-making reveals probabilistic cognition** (Shadlen & Kiani, 2013) +* **Social cognition scales with group structure** (Caporael, 1997) +* **Resilience involves cognitive reappraisal systems** (Kalisch et al., 2015) + +--- + +## Major Sources + +*Barsalou, L. W. (2008). Grounded cognition. Annual Review of Psychology, 59, 617–645. [https://doi.org/10.1146/annurev.psych.59.103006.093639](https://doi.org/10.1146/annurev.psych.59.103006.093639)* + +*Canli, T., & Lesch, K. P. (2007). Long story short: The serotonin transporter in emotion regulation and social cognition. Nature Neuroscience, 10(9), 1103–1109. [https://doi.org/10.1038/nn1964](https://doi.org/10.1038/nn1964)* + +*Caporael, L. R. (1997). The evolution of truly social cognition: The core configurations model. Personality and Social Psychology Review, 1(4), 276–298. [https://doi.org/10.1207/s15327957pspr0104_1](https://doi.org/10.1207/s15327957pspr0104_1)* + +*Dalley, J. W., Cardinal, R. N., & Robbins, T. W. (2004). Prefrontal executive and cognitive functions. Neuroscience & Biobehavioral Reviews, 28(7), 771–784. [https://doi.org/10.1016/j.neubiorev.2004.09.006](https://doi.org/10.1016/j.neubiorev.2004.09.006)* + +*Estes, W. K. (1994). Classification and Cognition. Oxford University Press.* + +*Hayes, J. P., VanElzakker, M. B., & Shin, L. M. (2012). Emotion and cognition interactions in PTSD. Frontiers in Integrative Neuroscience, 6, 89. [https://doi.org/10.3389/fnint.2012.00089](https://doi.org/10.3389/fnint.2012.00089)* + +*Kalisch, R., Müller, M. B., & Tüscher, O. (2015). A conceptual framework for the neurobiological study of resilience. Behavioral and Brain Sciences, 38, e92. [https://doi.org/10.1017/S0140525X1400082X](https://doi.org/10.1017/S0140525X1400082X)* + +*Posner, M. I., & Rothbart, M. K. (2007). Research on attention networks. Annual Review of Psychology, 58, 1–23. [https://doi.org/10.1146/annurev.psych.58.110405.085516](https://doi.org/10.1146/annurev.psych.58.110405.085516)* + +*Runco, M. A., & Chand, I. (1995). Cognition and creativity. Educational Psychology Review, 7(3), 243–267. [https://doi.org/10.1007/BF02213373](https://doi.org/10.1007/BF02213373)* + +*Schwarz, N., & Clore, G. L. (1996). Feelings and phenomenal experiences. In Social Psychology: Handbook of Basic Principles.* + +*Shadlen, M. N., & Kiani, R. (2013). Decision making as a window on cognition. Neuron, 80(3), 791–806. [https://doi.org/10.1016/j.neuron.2013.10.047](https://doi.org/10.1016/j.neuron.2013.10.047)* + +*Boyer, P. (2003). Religious thought and behaviour as by-products of brain function. Trends in Cognitive Sciences, 7(3), 119–124. [https://doi.org/10.1016/S1364-6613(03)00031-7](https://doi.org/10.1016/S1364-6613%2803%2900031-7)* + +*Lustig, C., Shah, P., Seidler, R., & Reuter-Lorenz, P. A. (2009). Aging, training, and the brain. Neuropsychology Review, 19, 504–522. [https://doi.org/10.1007/s11065-009-9119-9](https://doi.org/10.1007/s11065-009-9119-9)* + +--- + +## Final Insight + +Human cognition is: + +* Predictive +* Probabilistic +* Embodied +* Emotional +* Social +* Self-modeling +* Plastic +* Generative + +There is no clean separation between “rational” and “emotional” cognition. The literature consistently shows they are deeply integrated. + +--- + +If you'd like, we can next: + +* Create a **visual cognitive architecture map** +* Compare this taxonomy to AI cognitive architectures +* Analyze which processes are uniquely human +* Or apply one of the critical reading methods to a specific cognitive theory + +--- + + + +# What Remains Properly Human in AI-Enhanced Cognition? + +A deep synthesis of research on **human–AI collaboration, cognitive augmentation, distributed cognition, complementarity theory, and hybrid intelligence systems** converges on a critical conclusion: + +> AI excels at scale, pattern extraction, optimization, recall, and statistical inference. +> Humans remain primary in **value construction, meaning-making, ethical framing, embodied judgment, contextual reframing, and identity-driven creativity.** + +Across organizational science, cognitive psychology, hybrid intelligence research, and human–computer interaction, scholars identify a *complementarity structure* rather than substitution. AI handles computational depth; humans retain authority over direction, interpretation, and normative grounding. + +Below is a structured chart designed specifically to support **monitoring and delineation of human vs. AI contributions** in AI-augmented knowledge work. + +--- + +## Chart: Cognitive Capacities That Remain Properly Human + +*(For Monitoring Human–AI Interaction & Co-Evolution)* + +| Cognitive Domain | Human-Proper Capacities | Why AI Cannot Fully Replace | Monitoring Signals in Work Sessions | Co-Evolution Indicators | +| ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------- | +| **1. Value Framing & Normative Judgment** | Ethical evaluation, moral prioritization, responsibility attribution, defining “what should be done” | AI optimizes within goals; humans define goals and moral constraints | Moments where goals are set, constraints introduced, ethical concerns raised | Increasing clarity in prompting about values and constraints | +| **2. Meaning-Making & Narrative Integration** | Constructing coherent narratives, interpreting significance, contextualizing facts | AI generates text; humans assign existential or social meaning | User reframes outputs, restructures argument, injects personal stance | Development of stronger editorial voice | +| **3. Contextual Reframing** | Recognizing when a problem is mis-specified; redefining the question | AI works within prompt boundaries | User changes task framing, scope, or criteria | More strategic prompt restructuring | +| **4. Embodied & Experiential Judgment** | Tacit knowledge, intuition from lived experience, somatic markers | AI lacks embodied history and affective grounding | References to lived experience, “this feels wrong/right” | Increasing integration of personal insight into prompts | +| **5. Responsibility & Accountability** | Ownership of decisions and outcomes | AI lacks legal and moral agency | User signs off, modifies output before publication | Conscious differentiation of AI draft vs human approval | +| **6. Creative Direction & Taste** | Aesthetic preference, stylistic identity, originality selection | AI can generate options but cannot possess taste | Selection among alternatives, style refinement | Development of curated prompting style | +| **7. Strategic Intent & Long-Term Planning** | Defining personal/professional trajectory, aligning tasks with long-term identity | AI optimizes short-term tasks unless directed | User articulates vision or long-range plan | AI used as tool within broader human-defined roadmap | +| **8. Emotional Intelligence & Social Calibration** | Empathy, relational sensitivity, trust repair | AI simulates empathy; humans experience it | User adjusts tone for audience; detects emotional nuance | Improved prompt specificity about audience emotional state | +| **9. Identity Construction** | Self-concept development, authorship identity | AI lacks personal continuity | User reflects on “my voice,” “my position” | Increasing differentiation between AI assistance and self-expression | +| **10. Metacognitive Oversight** | Monitoring AI reliability, detecting hallucination, quality control | AI cannot independently verify its epistemic limits | User fact-checks, questions, cross-validates | Reduced blind acceptance; increased evaluative scrutiny | +| **11. Ethical Boundary Setting in AI Use** | Deciding acceptable delegation limits | AI cannot define ethical delegation boundaries | User chooses what not to outsource | Development of clear delegation policies | +| **12. Cross-Domain Analogical Leap** | Integrating disparate domains creatively | AI blends patterns statistically; humans introduce purpose-driven analogy | User introduces novel metaphor or conceptual bridge | Increasing hybrid creativity (human analogy + AI expansion) | +| **13. Ambiguity Tolerance & Existential Reflection** | Engaging with unresolved complexity | AI seeks pattern resolution | User explores paradox without closure | Growth in philosophical depth of prompts | +| **14. Collective & Cultural Interpretation** | Understanding cultural nuance and social impact | AI models patterns but lacks lived embeddedness | User adjusts for culture, ethics, politics | More precise cultural framing | + +--- + +## Structural Model: Human vs AI Division of Cognitive Labor + +### AI Dominant + +* Large-scale memory retrieval +* Statistical pattern detection +* Rapid drafting +* Formal logic scaffolding +* Data aggregation +* Simulation + +### Human Dominant + +* Goal definition +* Normative evaluation +* Meaning assignment +* Context shift +* Responsibility +* Long-term identity alignment +* Ethical boundaries +* Final authorship authority + +### Hybrid Zone (Co-Constructed) + +* Ideation +* Structured argument building +* Creative exploration +* Scenario analysis +* Refinement cycles + +Research consistently frames this as **complementarity rather than substitution** (Jarrahi 2018; Dellermann et al. 2019; Raisch & Krakowski 2021; Seeber et al. 2020). + +--- + +## Monitoring Framework for AI-Agent Oversight System + +To monitor human contribution during work sessions, an AI agent should track: + +### 1. Input Classification + +* Goal-setting statements +* Ethical constraints +* Reframing moves +* Selection decisions +* Edits made to AI output +* Emotional or value-laden language + +### 2. Cognitive Contribution Tagging + +Each interaction tagged as: + +* 🔹 Human framing +* 🔹 AI expansion +* 🔹 Human correction +* 🔹 Human synthesis +* 🔹 Human evaluative override +* 🔹 Hybrid construction + +### 3. Co-Evolution Metrics + +Track longitudinally: + +* Increasing prompt sophistication +* Reduction in blind acceptance +* Greater editorial intervention +* More structured delegation +* More explicit value articulation +* Emergence of new hybrid cognitive routines + +This aligns with **Hybrid Intelligence frameworks** emphasizing learning loops between human and AI (Dellermann et al., 2019). + +--- + +## Co-Evolution Model + +Human–AI cognitive partnership develops through stages: + +1. **Tool Use** – AI as assistant +2. **Cognitive Extension** – AI as scaffold +3. **Reflective Delegation** – human chooses boundaries +4. **Strategic Integration** – AI embedded in workflows +5. **Meta-Cognitive Partnership** – human monitors AI + self-development + +This resembles distributed cognition models (Hutchins, 1995) and complementarity theory (Raisch & Krakowski, 2021). + +--- + +## Key Sources + +*Jarrahi, M. H. (2018). Artificial intelligence and the future of work: Human-AI symbiosis in organizational decision making. Business Horizons, 61(4), 577–586. [https://doi.org/10.1016/j.bushor.2018.03.007](https://doi.org/10.1016/j.bushor.2018.03.007)* + +*Dellermann, D., Ebel, P., Söllner, M., & Leimeister, J. M. (2019). Hybrid intelligence. Business & Information Systems Engineering, 61, 637–643. [https://doi.org/10.1007/s12599-019-00595-2](https://doi.org/10.1007/s12599-019-00595-2)* + +*Raisch, S., & Krakowski, S. (2021). Artificial intelligence and management: The automation–augmentation paradox. Academy of Management Review, 46(1), 192–210. [https://doi.org/10.5465/amr.2018.0072](https://doi.org/10.5465/amr.2018.0072)* + +*Seeber, I., et al. (2020). Machines as teammates: A research agenda on AI in team collaboration. Information & Management, 57(2), 103174. [https://doi.org/10.1016/j.im.2019.103174](https://doi.org/10.1016/j.im.2019.103174)* + +*Hutchins, E. (1995). Cognition in the Wild. MIT Press.* + +*Shneiderman, B. (2020). Human-centered AI. International Journal of Human–Computer Interaction, 36(6), 495–504. [https://doi.org/10.1080/10447318.2020.1741118](https://doi.org/10.1080/10447318.2020.1741118)* + +*Boden, M. A. (2016). AI: Its Nature and Future. Oxford University Press.* + +*Wilson, R. A., & Clark, A. (2009). How to situate cognition. Philosophical Psychology, 22(1), 1–17. [https://doi.org/10.1080/09515080802567974](https://doi.org/10.1080/09515080802567974)* + +*Brynjolfsson, E., & McAfee, A. (2014). The Second Machine Age. Norton.* + +*Daugherty, P. R., & Wilson, H. J. (2018). Human + Machine. Harvard Business Review Press.* + +--- + +## Core Conclusion + +The irreducibly human contributions in AI-enhanced cognition are: + +* **Normative** +* **Contextual** +* **Embodied** +* **Identity-driven** +* **Responsibility-bearing** +* **Meaning-making** + +AI scales cognition. +Humans define its direction. + +--- + +If you would like next, we can: + +* Convert this into a **formal monitoring ontology** +* Design a **data schema for tracking human cognitive contributions** +* Build a **visual architecture diagram** +* Or construct a **maturity model for human–AI cognitive co-evolution** + +And on the 3rd response, I’ll also include the requested image marker for the review framework. + + From 42095caab846edef11a0e3aca1cb43c44ea9f737 Mon Sep 17 00:00:00 2001 From: Tiberius Brastaviceanu Date: Thu, 6 Aug 2026 15:16:52 -0400 Subject: [PATCH 03/18] docs(requirements): add Source-Valueflows integration design document Introduced a new document detailing the integration of the `vf:Source` primitive into the Nondominium's Valueflows model. This comprehensive design outlines the purpose, structure, and implications of the `vf:Source` for generative ecological systems, distinguishing it from existing primitives. Additionally, updated the Valueflows DSL documentation to clarify the distinction between the current and planned capabilities, emphasizing the future integration of the `vf:Source` within the Nondominium architecture. --- .../post-mvp/source-valueflows-integration.md | 986 ++++++++++++++++++ .../requirements/post-mvp/valueflows-dsl.md | 162 ++- 2 files changed, 1113 insertions(+), 35 deletions(-) create mode 100644 documentation/requirements/post-mvp/source-valueflows-integration.md diff --git a/documentation/requirements/post-mvp/source-valueflows-integration.md b/documentation/requirements/post-mvp/source-valueflows-integration.md new file mode 100644 index 0000000..0cbaf11 --- /dev/null +++ b/documentation/requirements/post-mvp/source-valueflows-integration.md @@ -0,0 +1,986 @@ +# Source–Valueflows Integration Design + +**Status**: Post-MVP design (implementation-informing) +**Created**: 2026-07-05 +**Relates to**: `[source-ndo-requirements.md](source-ndo-requirements.md)`, `[Source-NDO.md](Source-NDO.md)`, `[ndo_prima_materia.md](../ndo_prima_materia.md)`, `[specifications.md](../../specifications/specifications.md)` +**Normative requirements**: REQ-SOURCE-* in `[source-ndo-requirements.md](source-ndo-requirements.md)` + +--- + +## Purpose + +This document integrates the `vf:Source` primitive into nondominium's Valueflows model. It is structured as two deliberately separated discussions: + + +| Part | Scope | Audience | +| ------------------------- | ---------------------------------------- | ---------------------- | +| **Part I — Valueflows** | Implementation-agnostic ontology | Any REA/VF implementer | +| **Part II — Nondominium** | This Holochain hApp's Rust/TS data model | nondominium developers | + + +Parts III–IV apply both layers in a worked use case and concrete data model. Part V records open decisions before implementation. + +This document **does not modify zome code**. It informs Phase A–E implementation described in `source-ndo-requirements.md` [§9](source-ndo-requirements.md). + +--- + + + +Valueflows +> **Scope**: Pure ontology. No Holochain, no NDO layers, no governance-as-operator. Any Valueflows-compliant system could adopt this extension. + + + +## 1.1 Valueflows primitive recap + +Valueflows is an open vocabulary built on the REA (Resource–Event–Agent) accounting ontology. It models economic activity through three knowledge/plan/observation layers: + + +| VF layer | Purpose | Core types | +| --------------- | --------------------- | -------------------------------------------------------- | +| **Knowledge** | Types and templates | `ResourceSpecification`, `ProcessSpecification` (Recipe) | +| **Plan** | Intent and obligation | `Intent`, `Commitment`, `Agreement` | +| **Observation** | What happened | `EconomicEvent`, `Claim` | + + +**Agents** (`vf:Person`, `vf:Organization`, `vf:EcologicalAgent`) are entities that initiate, receive, commit to, and bear responsibility for economic flows. + +**Resources** (`vf:EconomicResource`) are inventoried instances conforming to a `ResourceSpecification`. Each resource may carry a `primaryAccountable` agent — the agent with primary rights and responsibilities (ownership/accounting association). + +**Events** (`vf:EconomicEvent`) record observed economic activity. Each event has: + +- `action` — one of the VF action vocabulary (`produce`, `consume`, `use`, `transfer`, `raise`, `lower`, …) +- `provider` — the agent from whom the flow is initiated +- `receiver` — the agent to whom the flow is directed +- `resourceInventoriedAs` / `affects` — the economic resource affected +- `resourceQuantity` — amount and unit + +**Processes** group inputs and outputs. **Commitments** promise future events; **Claims** link fulfilled events back to commitments. + +nondominium's MVP implements this pattern in `zome_gouvernance` (`EconomicEvent`, `Commitment`, `Claim`) and `zome_resource` (`ResourceSpecification`, `EconomicResource`), with 16 `VfAction` variants including nondominium extensions (`InitialTransfer`, `AccessForUse`, `TransferCustody`). + +## 1.2 The endpoint constraint (why the gap exists) + +The Valueflows specification defines typed ranges for flow endpoints. From the official ontology (`/valueflows/valueflows`, `all_vf.html`): + +```turtle +vf:provider + rdfs:comment "The economic agent from whom the intended, committed, or actual economic event is initiated." + rdfs:range vf:Agent . + +vf:receiver + rdfs:comment "The economic agent to whom the intended, committed, or actual economic event is directed." + rdfs:range vf:Agent . + +vf:primaryAccountable + rdfs:comment "The agent currently with primary rights and responsibilites for the economic resource." + rdfs:range vf:Agent . +``` + +**Consequence**: in Valueflows 1.0, every flow endpoint and every resource accountability anchor **must** be an `Agent`. Resources are inventoried outputs; they are never providers, receivers, or sinks for ecological loading. + +This is correct for appropriable economic outputs (water in a tank, fish landed, timber cut). It is **incorrect** for generative ecological systems (rivers, watersheds, forests, fisheries, knowledge commons) that: + +- **yield** resources without being owned +- **receive** pollution and ecological effects without possessing agency +- **condition** other generative systems (forest → river infiltration) +- accumulate an event ledger that should drive adaptive governance + + + +## 1.3 The ontological gap + +A river under a **nondominium** property regime fits neither category honestly: + + +| If modelled as… | Problem | +| ------------------------------- | ------------------------------------------------------------------------------------------------------ | +| `EconomicResource` | Requires `primaryAccountable` — a false ownership claim, the inverse of nondominium | +| `Agent` **/** `EcologicalAgent` | Attributes intention the river does not possess; human representatives speak for it | +| **Avoided entirely** | Abstraction appears as `raise` (resource from nowhere); depletion and pollution vanish from the ledger | + + +Ostrom's Social-Ecological Systems framework already distinguishes **resource system** (fishery, watershed) from **resource unit** (fish, gallons of water). Valueflows collapses both into `EconomicResource` + `Agent`, losing the resource-system category at the executable layer. + +### Three active fictions (Model A) + +Using Valueflows 1.0 as-is for a watershed commons produces: + +1. **False ownership** — `EconomicResource { primaryAccountable: StewardOrg }` records dominium in the ledger meant to be authoritative. +2. **Resource from nowhere** — `raise` creates water inventory with no provider; the river is never debited; sustainability is unaccountable. +3. **Resource/Agent contradiction** — river typed as Resource for extraction and as EcologicalAgent to receive MiningCo's effluent; one entity, two incompatible types. + + + +### Four inexpressible residues + +1. **Source hierarchy** — watershed → river cannot be expressed as generation (only containment or free text). +2. **Cross-source coupling** — forest conditions river flow; no native edge. +3. **Black-box epistemics** — no construct for "interior opaque; govern boundary only." +4. **Governance reflexivity** — events → policy → access rules cannot close on the ecological object itself. + +See `Source-NDO.md` [§3–§5](Source-NDO.md) for the full river/watershed worked comparison and Occam's-razor analysis. + +## 1.4 The `vf:Source` proposal + +`vf:Source` is a third ontological primitive alongside `Agent` and `EconomicResource`: + +``` +AGENT — acts, intends, commits, bears responsibility + (individuals, organisations, networks, bots) + +RESOURCE — appropriable, inventoriable output + (water in a tank, fish landed, timber cut, a design file in custody) + +SOURCE — generative system that yields Resources, receives effects, + conditions future possibilities, regenerates or degrades + (not owned, not an agent, not merely a stock behind a flow) +``` + +**Single new affordance**: *flows may originate from and terminate in Sources, not only in Agents or Resources.* + +At the RDF level this implies extending `vf:provider` and `vf:receiver` domains to include `vf:Source`, and introducing `vf:Source` as a class distinct from `vf:Agent` and `vf:EconomicResource`. Nondominium's implementation details are in Part II. + +### Ostrom mapping + + +| Ostrom / SES | vf:Source extension | +| ----------------- | ------------------------------------------------------------- | +| Resource system | **Source** | +| Resource unit | **Resource** (`EconomicResource`) | +| Governance system | Governance rules attached to Source (implementation-specific) | +| Users / actors | **Agent** | +| Action situation | **EconomicEvent**, Commitment, Claim | + + + + +## 1.5 Event shapes with Source endpoints + +Boundary events on a Source use standard VF actions with Source as provider or receiver: + +### Extraction (Source as provider) + +``` +EconomicEvent { + action: extract, // see §1.6 — VF core vocabulary note + provider: River (Source), + receiver: AgriCoop (Agent), + resourceConformsTo: WaterSpec, + resourceQuantity: 10000 m³ +} +→ decrements River.currentStock; depletion is visible +``` + + + +### Non-consumptive use (Source as provider of flux) + +``` +EconomicEvent { + action: use, + provider: River (Source), + receiver: HydroDam (Agent), + effect: River.regimeState // altered timing/sediment, not stock volume +} +``` + + + +### Pollution / loading (Source as receiver) + +``` +EconomicEvent { + action: produce, + provider: MiningCo (Agent), + receiver: River (Source), + resourceQuantity: 50 kg heavy metals +} +→ debits River.assimilationCapacity; pollution is visible +``` + + + +### Regeneration (Agent raises a Source) + +``` +EconomicEvent { + action: raise, + target: Forest (Source), + provider: RegenCollective (Agent), + resourceQuantity: 1000 trees +} +→ Forest.conditions(River): improved infiltration raises River.fluxRate and resilience +``` + + + +### Source-to-Source relations (not events — structural links) + +``` +Source --yields--> Source (watershed yields river) +Source --conditions--> Source (forest conditions river flow) +Source --yields--> Resource (river yields gallons when abstracted) +``` + + + +## 1.6 Action vocabulary note: `extract` + +Valueflows core actions include `consume`, `lower`, `raise`, `produce`, `use`, `transfer`, etc., but **no dedicated** `extract` **action**. Source-NDO literature uses `extract` informally for "withdraw from a generative system without transferring ownership." + + +| Option | Semantics | Trade-off | +| --------------------------------------------- | ----------------------------------------------------- | -------------------------------------------------------------------- | +| **Add** `Extract` to extended VF vocabulary | Clearest semantics for Source withdrawal | New action; all VF implementations must recognise it | +| **Map to** `Consume` | Resource leaves the Source and enters agent inventory | Conflates rivalrous depletion with generic consumption | +| **Map to** `Lower` | Decrements quantity at Source | Closest to stock debit; less intuitive for "yield to inventory" | +| **Map to** `Transfer` with Source as provider | Flow from Source to Agent | Requires Source as legal provider (the whole point of the extension) | + + +**Recommendation for nondominium**: add `Extract` as a 17th `VfAction` variant in `crates/shared/src/types.rs`, documented as "withdraw quantity from a Source into an inventoried Resource; debits Source condition state." This preserves semantic clarity for governance rules (`max extract per season`) and PPR categorisation. Until implemented, `Lower` on the Source plus `Raise`/`Transfer` on the derived Resource is an acceptable interim mapping. + +## 1.7 What the extension removes + + +| Removed | Description | +| ----------------------------------- | ----------------------------------------------------------------- | +| False ownership claim | Source has no `primaryAccountable`; stewardship ≠ dominium | +| Resource-from-nowhere `raise` | Extraction debits the Source; depletion is visible | +| Resource/Agent dual-typing | Source receives pollution without agency | +| Inexpressible source hierarchy | `Source yields Source` is a native edge | +| Inexpressible cross-source coupling | `Source conditions Source` is a native edge | +| Missing black-box epistemics | `complexInterior: true`, `regimeState` encode partial knowability | +| Missing governance reflexivity | Event ledger on Source → rules adapt → future events conditioned | + + + + +### Occam's razor verdict + +Adding **one** primitive (`vf:Source`) removes **three fictions and four residues**. Refusing to name the Source does not remove it from the world — it forces smuggling via mismatched parts. The augmented ontology is more parsimonious at the level that matters: the furniture of reality the model commits to. + +--- + + + +# Part II — Nondominium Discussion + +> **Scope**: How `vf:Source` lands on this hApp's Rust zomes, TypeScript shared types, governance-as-operator pattern, and NDO three-layer model. + + + +## 2.1 Current-state mapping + + +| Valueflows concept | nondominium implementation | Source gap | +| --------------------------------------- | ------------------------------------------------------------------------------------------- | ---------------------------------------------------- | +| `Agent` | `AgentPubKey` + `Person` (`zome_person`) | OK | +| `ResourceSpecification` | `ResourceSpecification` (`zome_resource`) | OK for inventoriable types | +| `EconomicResource` | `EconomicResource { custodian: AgentPubKey, … }` | `custodian` = ownership/custody fiction for Sources | +| `EconomicEvent.provider` | `AgentPubKey` | Cannot be a Source | +| `EconomicEvent.receiver` | `AgentPubKey` | Cannot receive pollution into a Source | +| `EconomicEvent.resource_inventoried_as` | `ActionHash` → `EconomicResource` | REQ-SOURCE-EVENT-01 also targets Source Layer 0 hash | +| `primaryAccountable` | `EconomicResource.custodian` | Inappropriate for Source-NDO | +| `Commitment` / `Claim` | `zome_gouvernance` entries | Need Source-aware evaluation | +| `GovernanceRule` | `rule_type: String`, `rule_data: String` | Untyped; sufficient for MVP adaptive rules | +| Layer 0 identity | `NondominiumIdentity` | Permanent anchor; Source-NDO uses same entry | +| NDO federation links | `NdoHardLink` (`Component`, `DerivedFrom`, `Supersedes`) | Cross-NDO; not Source coupling | +| `VfAction` | 16 variants in `crates/shared/src/types.rs` | No `Extract` | +| Design-system types | `SourceProfile`, `SourceType`, `SourceRegimeState` in `packages/ndo-ui/src/domain/types.ts` | UI scaffold only; not in Rust zomes yet | + + +Current `EconomicEvent` (ground truth): + +```rust +pub struct EconomicEvent { + pub action: VfAction, + pub provider: AgentPubKey, + pub receiver: AgentPubKey, + pub resource_inventoried_as: ActionHash, + pub affects: ActionHash, + pub resource_quantity: f64, + pub event_time: Timestamp, + pub note: Option, +} +``` + + + +## 2.2 Central design decision: Source as flow endpoint + +How does a Source participate as provider or receiver in an `EconomicEvent`? + +### Option A — `FlowEndpoint` enum (breaking) + +Replace `provider`/`receiver: AgentPubKey` with `FlowEndpoint { Agent(AgentPubKey), Source(ActionHash) }`. + +- **Pros**: Cleanest semantics; one field per role; aligns with vf:Source long-term. +- **Cons**: Breaking change to every existing event, commitment, test, and UI binding. + + + +### Option B — Additive optional fields (recommended) + +Keep existing Agent fields; add parallel Source fields: + +```rust +pub struct EconomicEvent { + // … existing fields … + pub source_provider: Option, // NondominiumIdentity Layer 0 hash + pub source_receiver: Option, +} +``` + +Integrity validation: exactly one of `{ provider, source_provider }` must be set for the initiating side; same for receiver. Agent–Agent events unchanged. + +- **Pros**: Non-breaking; post-MVP additive; Sweettest can cover Source events without migrating history. +- **Cons**: Two parallel representations; callers must check both fields. + + + +### Option C — Overload `resource_inventoried_as` / `affects` + +Per REQ-SOURCE-EVENT-01, point `resource_inventoried_as` at the Source's Layer 0 hash; infer provider/receiver role from `action` direction. + +- **Pros**: Minimal schema change. +- **Cons**: Overloads a field meant for inventoried resources; ambiguous for events affecting both Source and Resource; weak type safety. + +**Recommendation**: **Option B** for Phase B implementation; consider Option A as a major-version migration once Source events are stable. + +## 2.3 `SourceProfile` as Layer 0 extension + +REQ-SOURCE-ONT-04 and REQ-NDO-L0 immutability require Source condition state **not** on `NondominiumIdentity` itself. Implement as a separate entry linked from Layer 0: + +```rust +pub struct SourceProfile { + pub ndo_identity_hash: ActionHash, + pub source_type: SourceType, + pub regime_state: SourceRegimeState, + pub stewarded_by: Vec, + pub current_stock: Option, + pub flux_rate: Option, + pub assimilation_capacity: Option, + pub resilience: Option, + pub tipping_threshold: Option, + pub adaptive_capacity: Option, + pub generative_capacity: Option, + pub dependency_index: Option, + pub complex_interior: bool, + pub created_at: Timestamp, + pub last_condition_update: Timestamp, +} +``` + +**Link**: `NondominiumIdentity (action_hash) → SourceProfile` via `LinkTypes::NdoToSourceProfile`. + +**Archetype flag**: UI uses `ndo_archetype: "source_ndo"` (`packages/ndo-ui/src/domain/types.ts`); Rust may add an optional marker or infer from linked `SourceProfile`. + +**Layer 1**: `SourceSpecification` (boundary definitions, monitoring framework, ecological value vector) — activated when governance is formalised; links via future `NDOToSpecification`. + +Enums align with design-system TS: `SourceType`, `SourceRegimeState`, `EcologicalValueDimension`. + +## 2.4 Source-to-Source coupling links + +Distinct from `NdoHardLink` (cross-DNA federation). Intra-network ecological structure: + +```rust +pub enum SourceLinkType { Yields, Conditions, ProvidedBy } + +pub struct SourceCouplingLink { + pub from_source_hash: ActionHash, // Layer 0 hash + pub to_source_hash: ActionHash, + pub link_type: SourceLinkType, + pub coupling_strength: Option, + pub notes: Option, +} +``` + +Anchor: `SourceCoupling(from_hash, link_type) → to_hash`. + +## 2.5 Stewardship model + +Source-NDOs use **stewardship**, not custody or ownership: + + +| Concept | Standard NDO / Resource | Source-NDO | +| ----------------- | ---------------------------- | --------------------------------------------- | +| Holder | `EconomicResource.custodian` | Not applicable | +| Responsible party | `PrimaryAccountableAgent` | `SourceProfile.stewarded_by` | +| Role | `PrimaryAccountableAgent` | `Steward` (new `RoleType` variant) | +| Transfer | Custody transfer event | Stewardship succession (governance-validated) | + + +`Steward` carries **obligations** (monitoring, access decisions, rule implementation) without **alienation rights**. No steward can privatise a Source-NDO. Governance rejects rules asserting ownership (REQ-SOURCE-ONT-02). + +Current `RoleType` (`zome_person`): `SimpleAgent`, `AccountableAgent`, `PrimaryAccountableAgent`, `Transport`, `Repair`, `Storage`. Phase A adds `Steward`. + +## 2.6 Adaptive governance loop + +Extends governance-as-operator (`zome_gouvernance` evaluates; `zome_resource` holds data) into a **cybernetic loop** for complex Sources: + +``` +Boundary events (extract, load, restore, use) + ↓ +Event ledger (linked to Source Layer 0 hash) + ↓ +Ecological interpretation (stewards, scientists, community signals) + ↓ +GovernanceRule adaptation (versioned rule entries on Layer 1) + ↓ +Access affordances (quantitative constraints in rule_data JSON) + ↓ +Conditioned future events (governance operator blocks or requires approval) + ↓ (loop) +``` + +**Black-box principle**: stewards observe boundary signals (withdrawals, pollutant loads, sensor readings, narrative assessments) — not the full watershed interior. `SourceProfile.complex_interior: true` encodes this epistemic stance. + +**State updates** (REQ-SOURCE-EVENT-02): `current_stock`, `assimilation_capacity`, etc. are updated **only** through governance-validated transitions triggered by approved events — never by direct write from the extracting agent. + +Example affordance rule (`GovernanceRule`): + +```json +{ + "rule_type": "source_access_affordance", + "rule_data": { + "source_hash": "", + "agent_role": "AccountableAgent", + "action": "Extract", + "max_quantity_per_period": 8000, + "period": "season", + "resource_unit": "m3" + } +} +``` + + + +## 2.7 PropertyRegime constraints + +Source-NDOs **MUST** use `PropertyRegime::Nondominium` or `PropertyRegime::CommonPool` (REQ-SOURCE-ONT-02). Integrity validation on `create_ndo` when `SourceProfile` is linked should reject `Private`, `Commons`, `Pool`, `Collective` for Source archetypes. + +Governance operator rejects `GovernanceRule` entries that assert transferable ownership over a Source Layer 0 hash. + +## 2.8 VfAction extension + +Add to `crates/shared/src/types.rs`: + +```rust +Extract, // Withdraw from Source into inventoried Resource; debits Source condition +``` + +Semantic methods (mirroring existing `VfAction` helpers): + +- `Extract.requires_source_provider()` → true +- `Produce` with `source_receiver` → loading/pollution +- `Raise` with Source as `affects` → regeneration + + + +## 2.9 PPR mapping for Source interactions + + +| Activity | PPR category | +| -------------------------------------------- | ------------------------------------------------------------------- | +| Source-NDO registration + initial assessment | `ResourceCreation` | +| Monitoring data submission | `ValidationActivity` | +| Compliance with extract/discharge limits | `RuleCompliance` | +| Restoration commitment / fulfillment | `MaintenanceCommitmentAccepted` / `MaintenanceFulfillmentCompleted` | +| Dispute over condition or access | `DisputeResolutionParticipation` | +| Stewardship succession | `GoodFaithTransfer` | +| Regime state transition validation | `ValidationActivity` | + + +Stewardship participation accumulates governance standing via existing PPR → `ReputationSummary` path; no new PPR categories required for MVP. + +--- + + + +# Part III — Worked Use Case + +> Each scenario appears twice: abstract VF (Part I style) then nondominium instance data (Part II structures). + + + +## 3.1 River / watershed (primary) + + + +### The case + +A watershed feeds a river. Eight agents interact with conflicting interests: + + +| Agent | Interaction | Externality | +| ------------------- | ---------------------------- | ----------------------------------------------- | +| **AgriCoop** | Irrigation — consumes water | Nutrient runoff (N, P) downstream | +| **CityUtility** | Public water supply | Needs clean water; harmed by upstream pollution | +| **MiningCo** | Abstraction + effluent | Heavy metals; conflicts with agriculture | +| **HydroDam** | Non-consumptive flow use | Alters timing; starves downstream agriculture | +| **FisherGuild** | Fish extraction | Overfishing degrades biological regime | +| **RiverTours** | Recreation / transport | Low impact; harmed by pollution and low flow | +| **ForestryOp** | Watershed logging | Reduces infiltration → flow and quality | +| **RegenCollective** | Reforestation, riparian work | Raises generative capacity of coupled Sources | + + +Governance goal: align agents toward sustainable use — Ostrom commons stewardship extended into the **complex** domain (probe–sense–respond, not design-once rules). + +### Source hierarchy + +``` +WATERSHED (complex system — black box) + ├── RIVER (sub-source) ── yields ──► water m³ (EconomicResource) + ├── FOREST (sub-source) ── yields ──► timber (EconomicResource) + │ └── conditions RIVER + ├── FAUNA (sub-source) ── yields ──► fish + └── FLORA (sub-source) ── yields ──► herbs +``` + + + +### Model A breaks (VF 1.0 as-is) + +**Fiction 1 — false ownership** + +``` +EconomicResource River { primaryAccountable: StewardOrg } +EconomicEvent { action: transfer, provider: StewardOrg, receiver: AgriCoop, quantity: 10000 m³ } +``` + +Records dominium in the authoritative ledger; violates nondominium property regime. + +**Fiction 2 — depletion invisible** + +``` +EconomicEvent { action: raise, resourceInventoriedAs: Water#agri, quantity: 10000 m³ } +// provider: none — river never debited +``` + +**Fiction 3 — pollution dual-typing** + +``` +EconomicEvent { action: produce, provider: MiningCo, receiver: ??? } +// River-as-Resource cannot receive → forced EcologicalAgent typing +``` + +**Residues**: no `Watershed yields River` edge; no `Forest conditions River`; no `complexInterior`; no closed governance loop on the river object. + +### Model B — vf:Source (abstract VF) + +``` +// Abstraction — depletion visible +EconomicEvent { action: extract, provider: River(Source), receiver: AgriCoop, quantity: 10000 m³ } + +// Pollution — loading visible +EconomicEvent { action: produce, provider: MiningCo, receiver: River(Source), quantity: 50 kg } + +// Regeneration — cross-source coupling +EconomicEvent { action: raise, provider: RegenCollective, target: Forest(Source), quantity: 1000 trees } +→ Forest.conditions(River): fluxRate ↑, resilience ↑ +``` + + + +### nondominium instance data + +Three Source-NDOs registered in a Group via `create_ndo` + linked `SourceProfile`: + + +| NDO | `property_regime` | `source_type` | Key `SourceProfile` fields | +| ------------- | ----------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| **Watershed** | `Nondominium` | (parent) | `complex_interior: true`, `regime_state: Stable` | +| **River** | `Nondominium` | `Hydrological` | `current_stock: 5_000_000 m³`, `flux_rate: 120_000 m³/month`, `assimilation_capacity: 500 kg`, `stewarded_by: [WatershedCouncil, RiverKeepers]` | +| **Forest** | `Nondominium` | `Biological` | `current_stock: 0.85` (canopy index), `resilience: 0.72`, `stewarded_by: [ForestryBoard]` | + + +**Coupling links** (`SourceCouplingLink`): + + +| from | link_type | to | coupling_strength | +| --------- | ------------ | ------ | ----------------- | +| Watershed | `Yields` | River | — | +| Watershed | `Yields` | Forest | — | +| Forest | `Conditions` | River | 0.68 | + + +**Sample events** (Option B schema): + + +| # | action | provider | receiver | source_provider | source_receiver | affects (Layer 0) | qty | Effect | +| --- | --------- | --------------- | --------------- | --------------- | --------------- | ----------------- | ---------- | ---------------------------------------------------- | +| E1 | `Extract` | AgriCoop | AgriCoop | — | — | River | 10_000 m³ | `current_stock` −10_000 | +| E2 | `Produce` | MiningCo | — | — | River | River | 50 kg | `assimilation_capacity` −50 | +| E3 | `Raise` | RegenCollective | RegenCollective | — | — | Forest | 1000 trees | Forest stock ↑; propagates to River via `Conditions` | + + +**Governance rules** (Layer 1, `GovernanceRule`): + + +| rule_id | type | summary | +| --------- | ------------------------------ | -------------------------------------------- | +| R-2026-03 | `source_access_affordance` | MiningCo: max 10 kg/month pollutants | +| R-2026-04 | `source_access_affordance` | AgriCoop: max 8000 m³/season extract | +| R-2026-05 | `source_monitoring_obligation` | Extractors must submit monthly flow readings | + + +After E1–E3 accumulate on the River ledger, stewards revise R-2026-04 downward if `regime_state` transitions toward `Stressed` (REQ-SOURCE-GOV-05). + +--- + + + +## 3.2 Knowledge commons (parallel) + +Shows `vf:Source` generalises beyond ecology — directly relevant to nondominium's design-file and open-hardware NDOs. + +### The case + +**OpenCNC Designs** — an open-source CNC machine design repository under `PropertyRegime::Nondominium`, `SourceType::KnowledgeCommons`. + + +| Agent | Interaction | +| ----------------- | ------------------------------------- | +| **DesignerAlice** | Contributes CAD files | +| **FabLabBerlin** | Forks design for local materials | +| **PartSupplier** | Fabricates parts from published specs | +| **MaintainerBob** | Curates quality, merges contributions | + + + + +### VF abstract + +``` +Source OpenCNC { + source_type: KnowledgeCommons, + complex_interior: false, // designs are inspectable unlike watershed + stewarded_by: [MaintainerBob, DesignCouncil] +} + +// Contribution enriches the Source +EconomicEvent { action: work, provider: DesignerAlice, receiver: OpenCNC(Source) } + +// Fork creates derived Source coupled to parent +Source FabLabFork --providedBy--> OpenCNC +Source OpenCNC --yields--> ResourceSpecification "CNC-v3.2" + +// Fabrication extracts inventoriable instance from Source +EconomicEvent { action: extract, provider: OpenCNC(Source), receiver: PartSupplier, + resourceConformsTo: CNC-v3.2, quantity: 1 } +``` + +Non-rival: `extract` copies the design without depleting the Source (`current_stock` unchanged; `generative_capacity` and `dependency_index` track usage). + +### nondominium instance data + + +| NDO | `resource_nature` | `source_type` | Notes | +| --------------------- | ----------------- | ------------------ | ------------------------------------------ | +| **OpenCNC** | `Information` | `KnowledgeCommons` | `flux_rate: N/A`, `dependency_index: 0.45` | +| **FabLabBerlin-Fork** | `Information` | `KnowledgeCommons` | `ProvidedBy → OpenCNC` | + + + +| Event | action | Flow | Effect | +| ----- | --------- | ----------------------------------------- | ---------------------------------------------------------------- | +| K1 | `Work` | DesignerAlice → OpenCNC (source_receiver) | Contribution logged; `LearningValue` ↑ | +| K2 | `Extract` | OpenCNC (source_provider) → PartSupplier | New `EconomicResource` instance; Source undiminished | +| K3 | `Cite` | FabLabFork → OpenCNC | Attribution edge; `Conditions` coupling for upstream propagation | + + +Governance: `GovernanceRule` requires `Cite` on fork; `RuleCompliance` PPR for maintainers enforcing attribution. + +--- + + + +# Part IV — Data Model + + + +## 4.1 Three-primitive relationship diagram + +```mermaid +graph LR + Agent["Agent (Person / Organization)"] + Event["EconomicEvent"] + Resource["EconomicResource"] + Source["Source-NDO (NondominiumIdentity + SourceProfile)"] + + Agent -->|"provider / receiver (AgentPubKey)"| Event + Source -->|"source_provider / source_receiver (Layer0 hash)"| Event + Event -->|"affects"| Resource + Event -->|"affects"| Source + Source -->|"yields"| Resource + Source -->|"yields"| Source + Source -->|"conditions"| Source + Agent -->|"stewarded_by"| Source +``` + + + + + +## 4.2 Entity definitions (design-level Rust) + + + +### Enums (`crates/shared/src/types.rs` — proposed additions) + +```rust +pub enum SourceType { + Hydrological, + Biological, + Atmospheric, + KnowledgeCommons, + SocialCommons, +} + +pub enum SourceRegimeState { + Pristine, + Stable, + Stressed, + Degraded, + Critical, + Transformed, +} + +pub enum SourceLinkType { + Yields, + Conditions, + ProvidedBy, +} + +// VfAction extension +// Extract, // add to existing enum +``` + + + +### `SourceProfile` (`zome_resource` integrity — proposed) + +See §2.3. Linked from `NondominiumIdentity` action hash. Updated only via governance-validated coordinator functions (`apply_source_condition_update`). + +### Extended `EconomicEvent` (`zome_gouvernance` integrity — Option B) + +```rust +pub struct EconomicEvent { + pub action: VfAction, + pub provider: AgentPubKey, + pub receiver: AgentPubKey, + pub source_provider: Option, + pub source_receiver: Option, + pub resource_inventoried_as: ActionHash, + pub affects: ActionHash, + pub resource_quantity: f64, + pub event_time: Timestamp, + pub note: Option, +} +``` + +Integrity rules: + +- `(provider set XOR source_provider set)` for initiating side when action requires a provider +- `(receiver set XOR source_receiver set)` for receiving side when action requires a receiver +- `affects` MUST reference either an `EconomicResource` or a Source Layer 0 `NondominiumIdentity` hash (discriminated by link presence of `SourceProfile`) +- Agent–Agent events: both Source fields `None` (backward compatible) + + + +### `SourceCouplingLink` (`zome_resource` integrity — proposed) + +See §2.4. + +### TypeScript mirror (`packages/ndo-ui/src/domain/types.ts`) + +Existing types `SourceProfile`, `SourceType`, `SourceRegimeState`, `EcologicalValueDimension`, `NdoArchetypeId::source_ndo` remain the UI contract. Backend implementation must serialize compatibly. + +## 4.3 River instance graph + +```mermaid +graph TD + Watershed["Watershed NDO + SourceProfile"] + River["River NDO + SourceProfile"] + Forest["Forest NDO + SourceProfile"] + WaterRes["EconomicResource: water m3"] + AgriCoop["AgriCoop Agent"] + MiningCo["MiningCo Agent"] + RegenColl["RegenCollective Agent"] + + Watershed -->|Yields| River + Watershed -->|Yields| Forest + Forest -->|Conditions 0.68| River + River -->|yields on extract| WaterRes + AgriCoop -->|E1 Extract| River + MiningCo -->|E2 Produce into| River + RegenColl -->|E3 Raise| Forest +``` + + + + + +### Concrete instance rows + +**NDO Layer 0** + + +| hash (example) | name | property_regime | lifecycle_stage | +| --------------- | ---------------- | --------------- | --------------- | +| `ndo:watershed` | Alpine Watershed | Nondominium | Active | +| `ndo:river` | Alpine River | Nondominium | Active | +| `ndo:forest` | Alpine Forest | Nondominium | Active | + + +**SourceProfile snapshots (after E1–E3)** + + +| source | current_stock | assimilation_capacity | resilience | regime_state | +| ------ | ------------- | --------------------- | ---------- | ------------ | +| River | 4_990_000 m³ | 450 kg | 0.71 | Stable | +| Forest | 0.87 canopy | — | 0.74 | Stable | + + +**Events** + +``` +E1: { action: Extract, provider: AgriCoop, source_provider: ndo:river, + affects: ndo:river, quantity: 10000, unit: m3, event_hash: evt:e1 } + +E2: { action: Produce, provider: MiningCo, source_receiver: ndo:river, + affects: ndo:river, quantity: 50, unit: kg, note: "heavy metals", event_hash: evt:e2 } + +E3: { action: Raise, provider: RegenCollective, affects: ndo:forest, + quantity: 1000, unit: trees, event_hash: evt:e3 } +``` + +**GovernanceRule rows** + +``` +R-2026-04: { max_extract_m3_per_season: 8000, source: ndo:river, enforced_by: "Steward" } +R-2026-03: { max_load_kg_per_month: 10, source: ndo:river, pollutant: "heavy_metals" } +``` + + + +## 4.4 Knowledge-commons instance rows + + +| hash | name | source_type | property_regime | +| ----------------- | ------------------ | ---------------- | --------------- | +| `ndo:opencnc` | OpenCNC Designs | KnowledgeCommons | Nondominium | +| `ndo:fablab-fork` | FabLab Berlin Fork | KnowledgeCommons | Nondominium | + + + +| link | type | +| --------------------------------- | ------------ | +| `ndo:fablab-fork` → `ndo:opencnc` | `ProvidedBy` | + + + +| Event | Effect on SourceProfile | +| ----------------------------- | ----------------------------------------- | +| K1 Work into OpenCNC | `ecological_values.LearningValue` ↑ | +| K2 Extract spec to fabricator | `dependency_index` ↑; stock unchanged | +| K3 Cite on fork | attribution recorded; coupling maintained | + + + + +## 4.5 Data-relationship walkthrough + + + +### Extract debits stock (E1) + +1. AgriCoop submits `Extract` with `source_provider = ndo:river`. +2. Governance operator evaluates R-2026-04: 10_000 > 8_000 seasonal cap → **reject** OR multi-validator override if emergency. +3. If approved: create `EconomicEvent`; link `NdoToTransitionEvent` / Source event anchor on `ndo:river`. +4. Coordinator calls `apply_source_condition_update`: `current_stock -= 10000`. +5. Check `tipping_threshold`: if `current_stock / flux_rate` ratio critical → block further extracts (REQ-SOURCE-GOV-03). +6. Issue PPRs: AgriCoop `RuleCompliance` or violation record; stewards `ValidationActivity` if monitoring submitted. + + + +### Raise propagates via Conditions (E3) + +1. RegenCollective `Raise` on `ndo:forest` approved. +2. `SourceProfile` for Forest: canopy index ↑, `resilience` ↑. +3. Traverse `SourceCouplingLink { Forest → Conditions → River }` with `coupling_strength: 0.68`. +4. Derived update on River: `flux_rate += delta * 0.68`, `resilience += delta * 0.68` (formula configurable in governance module). +5. River ledger now shows regeneration pathway — forest–river sustainability is an **accounting fact**, not external analysis. + +--- + + + +# Part V — Open Questions and Traceability + + + +## 5.1 Pre-implementation decisions + + +| # | Question | Options | Recommendation | +| --- | ---------------------------- | ----------------------------------------- | --------------------------------------------------- | +| 1 | Flow endpoint representation | A enum / B additive / C overload | **B** now; A at major version | +| 2 | `Extract` action | New variant / map to `Lower` | **New** `Extract` **variant** | +| 3 | `SourceProfile` shape | Monolithic / split state vs value-vector | Monolithic MVP; split Layer 1 value vector later | +| 4 | Stock update authority | Agent-writable / governance-only | **Governance-validated only** (REQ-SOURCE-EVENT-02) | +| 5 | Cross-DNA Source hierarchy | Same cell links / `NdoHardLink` extension | Phase E: extend federation pattern | +| 6 | `affects` typing | Tag link / separate field `affects_kind` | Tag link `SourceProfile` presence discriminates | +| 7 | Fauna/Flora sub-sources | Separate NDOs / folded into Forest | Separate NDOs when distinct governance needed | + + + + +## 5.2 Implementation phasing (from REQ doc) + + +| Phase | This document section | Deliverable | +| ----- | --------------------- | ---------------------------------------------------------- | +| **A** | §2.3, §2.4, §2.5 | `SourceProfile`, enums, coupling links, `Steward` role | +| **B** | §2.2, §2.8, §4.5 | Option B event fields, `Extract`, boundary event recording | +| **C** | §2.6 | Adaptive loop, regime transitions, affordance rules | +| **D** | §3.2, Layer 1 | Ecological value vector, PPR integration | +| **E** | §5.1 #5 | Cross-DNA watershed federation | + + + + +## 5.3 REQ-SOURCE-* traceability + + +| Requirement | Addressed in | +| ------------------------ | -------------------------- | +| REQ-SOURCE-ONT-01 | Part I §1.4; Part II §2.2 | +| REQ-SOURCE-ONT-02 | Part II §2.5, §2.7 | +| REQ-SOURCE-ONT-03 | Part II §2.4; Part IV §4.2 | +| REQ-SOURCE-ONT-04 | Part II §2.3; Part IV §4.3 | +| REQ-SOURCE-DATA-01 | Part II §2.3; Part IV §4.2 | +| REQ-SOURCE-DATA-02 | Part II §2.6; Part IV §4.5 | +| REQ-SOURCE-DATA-03 | Part III §3.2; Phase D | +| REQ-SOURCE-GOV-01 – 08 | Part II §2.6 | +| REQ-SOURCE-EVENT-01 – 03 | Part II §2.2; Part IV §4.5 | + + + + +## 5.4 Related documents + + +| Document | Role | +| -------------------------------------------------------------------- | ---------------------------------------------------- | +| `[source-ndo-requirements.md](source-ndo-requirements.md)` | Normative REQ-SOURCE-* requirements | +| `[Source-NDO.md](Source-NDO.md)` | Academic grounding, river case study, Occam analysis | +| `[ndo_prima_materia.md](../ndo_prima_materia.md)` | NDO three-layer model, Layer 0 invariants | +| `[specifications.md](../../specifications/specifications.md)` | MVP `EconomicEvent`, governance-as-operator | +| [Valueflows specification](https://github.com/valueflows/valueflows) | VF 1.0 ontology baseline | + + +--- + +*This design document extends Valueflows at the flow-endpoint level and maps the extension onto nondominium's existing NDO, governance-as-operator, and PPR architecture without breaking Layer 0 permanence or MVP event history.* \ No newline at end of file diff --git a/documentation/requirements/post-mvp/valueflows-dsl.md b/documentation/requirements/post-mvp/valueflows-dsl.md index 117e8d4..fbfaa88 100644 --- a/documentation/requirements/post-mvp/valueflows-dsl.md +++ b/documentation/requirements/post-mvp/valueflows-dsl.md @@ -4,14 +4,16 @@ | | | | ---------------- | ---------------------------------------------------------------------------- | -| **Project** | Nondominium — ValueFlows-compliant Resource Sharing Holochain Application | +| **Project** | Nondominium — Valueflows-compliant Resource Sharing Holochain Application | | **Organization** | Sensorica Open Value Network | | **Authors** | Sacha Pignot (Soushi888), Tibi | | **Status** | Draft — For Community Review | | **Version** | 1.0 (2025-12-28) | | **Repository** | [github.com/sensorica/nondominium](https://github.com/sensorica/nondominium) | -> **Technical Specifications**: See [ValueFlows DSL Technical Specifications](../specifications/valueflows-dsl-specs.md) for implementation details, syntax specifications, and technical architecture. +> **Technical Specifications**: See [Valueflows DSL Technical Specifications](../specifications/valueflows-dsl-specs.md) for implementation details, syntax specifications, and technical architecture. + +> **Scope note (ValueFlows version)**: This document specifies a DSL for **ValueFlows 1.0** — the current, ratified vocabulary that Nondominium implements today (two flow-endpoint primitives: `Agent` and `EconomicResource`). A separate, in-progress design proposes an **augmented ValueFlows** profile that adds a third primitive, **`vf:Source`**, for generative non-ownable systems (watersheds, forests, knowledge commons). Anywhere this document refers to `Source`, `vf:Source`, `extract`, or Source-NDOs, it is describing **future/work-in-progress** capability, not the MVP DSL. See [`source-valueflows-integration.md`](source-valueflows-integration.md) and [`source-ndo-requirements.md`](source-ndo-requirements.md). The delineation is made explicit throughout (see §2.1.1). --- @@ -35,21 +37,21 @@ ## 1. Executive Summary -This document specifies the requirements for a Domain-Specific Language (DSL) designed to express ValueFlows economic patterns within the Nondominium ecosystem. The DSL aims to provide power users, network administrators, and developers with a concise, human-readable scripting language for bootstrapping networks, bulk resource registration, process recipe definition, and automated economic coordination. +This document specifies the requirements for a Domain-Specific Language (DSL) designed to express Valueflows economic patterns within the Nondominium ecosystem. The DSL aims to provide power users, network administrators, and developers with a concise, human-readable scripting language for bootstrapping networks, bulk resource registration, process recipe definition, and automated economic coordination. -Nondominium is a ValueFlows-compliant Holochain application implementing distributed, agent-centric resource management with embedded governance. While a graphical user interface serves daily operations, complex administrative tasks—such as initializing a new commons network with dozens of resources, members, and governance rules—benefit significantly from a scriptable approach. +Nondominium is a Valueflows-compliant Holochain application implementing distributed, agent-centric resource management with embedded governance. While a graphical user interface serves daily operations, complex administrative tasks—such as initializing a new commons network with dozens of resources, members, and governance rules—benefit significantly from a scriptable approach. -The proposed DSL bridges the gap between the formal ValueFlows ontology and practical operational needs, enabling reproducible configurations, version-controlled economic definitions, and automated workflows that would be tedious or error-prone through manual GUI interaction. +The proposed DSL bridges the gap between the formal Valueflows ontology and practical operational needs, enabling reproducible configurations, version-controlled economic definitions, and automated workflows that would be tedious or error-prone through manual GUI interaction. --- ## 2. Background and Context -### 2.1 ValueFlows Overview +### 2.1 Valueflows Overview -ValueFlows is an open vocabulary for distributed economic networks, built upon the Resource-Event-Agent (REA) accounting ontology. It provides a standardized way to describe economic activity across organizational boundaries, enabling coordination between agents who may use different software systems. +Valueflows is an open vocabulary for distributed economic networks, built upon the Resource-Event-Agent (REA) accounting ontology. It provides a standardized way to describe economic activity across organizational boundaries, enabling coordination between agents who may use different software systems. -Core ValueFlows concepts include: +Core Valueflows concepts include: - **Agents** — Persons, organizations, or ecological agents that perform economic activities - **Resources** — Economic resources tracked by specification (type) and optionally as inventoried instances @@ -59,9 +61,27 @@ Core ValueFlows concepts include: - **Intents** — Desired economic events not yet committed (offers and requests) - **Recipes** — Templates defining how processes transform inputs to outputs +### 2.1.1 ValueFlows 1.0 vs. Augmented ValueFlows (planned) + +The DSL specified in this document targets **ValueFlows 1.0**. Understanding the boundary between the ratified standard and the planned augmentation matters for scoping the DSL grammar and its compilation targets. + +**ValueFlows 1.0 (current — the DSL's baseline).** The standard recognizes exactly **two flow-endpoint primitives**: `Agent` and `EconomicResource`. Every `EconomicEvent` has a `provider` and a `receiver`, both of which are strictly typed to `vf:Agent` in the specification; appropriable outputs are `EconomicResource`s with a `primaryAccountable` agent. This is what Nondominium's `zome_gouvernance` and `zome_resource` implement today (`EconomicEvent.provider`/`receiver` are `AgentPubKey`; `EconomicResource.custodian` is an `AgentPubKey`). All MVP DSL constructs in §6 compile to this model. + +**Augmented ValueFlows (planned / work-in-progress — NOT part of the MVP DSL).** A separate design proposes a **third primitive, `vf:Source`** — a generative, non-ownable, partially unknowable system that yields resources, receives effects, and conditions future possibilities (e.g. a river/watershed or a knowledge commons). Sources become valid flow endpoints and introduce an `extract` action, coupling links between Sources, a `Steward` functional role, and an adaptive (black-box) governance loop. This work is fully specified in [`source-valueflows-integration.md`](source-valueflows-integration.md) and [`source-ndo-requirements.md`](source-ndo-requirements.md). + +| Aspect | ValueFlows 1.0 (DSL baseline) | Augmented ValueFlows (planned) | +| --- | --- | --- | +| Flow-endpoint primitives | `Agent`, `EconomicResource` | + `vf:Source` | +| `EconomicEvent` endpoints | `provider`/`receiver` → `Agent` | endpoints may also be a `Source` | +| Actions | standard VF action set (§6.1.4) | + `extract` (draw yield from a Source) | +| Governance target | agent-held resources | + adaptive stewardship of Sources | +| DSL status | **in scope for MVP** | **future — grammar reserved, not implemented** | + +Throughout the remainder of this document, any construct that touches `Source` is flagged **(Planned — Augmented ValueFlows)** and is out of scope for the MVP DSL grammar. It is documented here so the DSL's syntax and roadmap reserve room for it without committing to implementation. + ### 2.2 Nondominium Architecture -Nondominium implements ValueFlows on Holochain through a three-zome architecture: +Nondominium implements Valueflows on Holochain through a three-zome architecture: - **zome_person** — Agent identity, profiles, roles, and capability-based access control - **zome_resource** — Resource specifications, economic resources, and lifecycle management @@ -75,7 +95,7 @@ Current limitations that the DSL addresses: - **Manual repetition** — Registering many resources or agents requires repetitive GUI interactions - **No reproducibility** — Network configurations cannot be version-controlled or replicated -- **Steep learning curve** — Understanding ValueFlows requires navigating verbose JSON-LD or GraphQL structures +- **Steep learning curve** — Understanding Valueflows requires navigating verbose JSON-LD or GraphQL structures - **No automation** — Recurring administrative tasks cannot be scripted - **Testing complexity** — Creating realistic test environments requires manual setup @@ -85,7 +105,7 @@ Current limitations that the DSL addresses: ### 3.1 Primary Goals -- **Accessibility** — Lower the barrier to working with ValueFlows patterns through readable, intuitive syntax +- **Accessibility** — Lower the barrier to working with Valueflows patterns through readable, intuitive syntax - **Efficiency** — Enable bulk operations that would be impractical through GUI interaction - **Reproducibility** — Allow network configurations to be version-controlled, shared, and replicated - **Correctness** — Provide compile-time validation of economic logic before execution @@ -93,9 +113,9 @@ Current limitations that the DSL addresses: ### 3.2 Secondary Goals -- **Contribution to ValueFlows ecosystem** — Design the DSL to potentially benefit other ValueFlows implementations -- **Educational value** — Help users understand ValueFlows concepts through practical usage -- **Extensibility** — Support future additions to the ValueFlows vocabulary and Nondominium features +- **Contribution to Valueflows ecosystem** — Design the DSL to potentially benefit other Valueflows implementations +- **Educational value** — Help users understand Valueflows concepts through practical usage +- **Extensibility** — Support future additions to the Valueflows vocabulary and Nondominium features --- @@ -125,7 +145,7 @@ Current limitations that the DSL addresses: - Defining complex process recipes - Automating recurring administrative tasks -**Other ValueFlows Implementers** — Projects building ValueFlows-based systems who may adopt or adapt the DSL for their own use cases. +**Other Valueflows Implementers** — Projects building Valueflows-based systems who may adopt or adapt the DSL for their own use cases. --- @@ -185,7 +205,7 @@ Current limitations that the DSL addresses: - Export current network state as DSL scripts - Diff two states to generate migration scripts -- Import from other ValueFlows implementations +- Import from other Valueflows implementations - Generate JSON-LD or GraphQL representations --- @@ -194,7 +214,7 @@ Current limitations that the DSL addresses: ### 6.1 Language Primitives -The DSL must support the following ValueFlows concepts as first-class language constructs: +The DSL must support the following **ValueFlows 1.0** concepts as first-class language constructs. (The `Source` primitive is a planned augmentation — see §6.1.7 — and is not part of the MVP grammar.) #### 6.1.1 Agents @@ -220,7 +240,7 @@ The DSL must support the following ValueFlows concepts as first-class language c #### 6.1.4 Actions -All standard ValueFlows actions must be supported: +All standard ValueFlows 1.0 actions must be supported: - **Process actions:** produce, consume, use, cite, work, deliverService, modify - **Transfer actions:** transfer, transferAllRights, transferCustody @@ -228,6 +248,8 @@ All standard ValueFlows actions must be supported: - **Combination actions:** combine, separate - **Adjustment actions:** raise, lower, copy +> **(Planned — Augmented ValueFlows)** The augmented profile adds an **`extract`** action for drawing yield from a `vf:Source` (e.g. abstracting water from a watershed, downloading a design from a commons repository). `extract` is **not** part of the MVP DSL action set; it is reserved for the future Source work. See [`source-valueflows-integration.md`](source-valueflows-integration.md). + #### 6.1.5 Processes and Recipes - Process specifications (types) @@ -242,6 +264,20 @@ All standard ValueFlows actions must be supported: - Booking and usage limits - Private Participation Receipts (PPR) configuration +#### 6.1.7 Sources — (Planned — Augmented ValueFlows, WIP) + +> **Not part of the MVP DSL.** The following constructs are reserved for the future augmented-ValueFlows profile and are documented so the grammar can accommodate them later without breaking changes. Full requirements live in [`source-valueflows-integration.md`](source-valueflows-integration.md) and [`source-ndo-requirements.md`](source-ndo-requirements.md). + +When the `vf:Source` primitive is adopted, the DSL is expected to add: + +- **Source declarations** — a generative system (e.g. `Hydrological`, `KnowledgeCommons`) with a `SourceProfile` (regime state, stock/flux, stewards, coupling links), modeled as a Layer 0 NDO extension +- **`extract` events** — events whose provider or receiver is a `Source` rather than an `Agent` +- **Source coupling links** — typed relationships between Sources (`Yields`, `Conditions`, etc.) so effects propagate across a watershed or dependency graph +- **`Steward` role assignments** — a functional role emphasizing obligations toward a Source rather than rights over a resource +- **Adaptive governance blocks** — rules that observe boundary events on a Source and adapt (black-box governance loop) + +The grammar should treat these as an optional, versioned language extension gated behind the augmented-ValueFlows profile, keeping the MVP declarative core (§6.1.1–6.1.6) unchanged. + ### 6.2 Operations #### 6.2.1 CRUD Operations @@ -287,7 +323,7 @@ _See technical specifications for detailed validation pipeline architecture._ ### 7.1 Usability -- Syntax should be readable by non-programmers familiar with ValueFlows concepts +- Syntax should be readable by non-programmers familiar with Valueflows concepts - Error messages must reference source locations and suggest corrections - Documentation with examples for all major use cases - Syntax highlighting support for common editors (VS Code, Vim, Emacs) @@ -320,7 +356,7 @@ _See technical specifications for detailed optimization strategies._ ### 7.4 Extensibility -- Support for custom attributes beyond core ValueFlows +- Support for custom attributes beyond core Valueflows - Plugin architecture for additional compilation targets - Versioned language specification for backward compatibility @@ -348,11 +384,11 @@ _See technical specifications for detailed security model._ - **Primary target**: Nondominium hREA zome calls - **Secondary targets**: JSON-LD export, GraphQL mutations, visualization -### 8.2 ValueFlows Compliance +### 8.2 Valueflows Compliance -- DSL concepts must map cleanly to ValueFlows vocabulary -- Terminology should align with ValueFlows documentation -- Export to standard ValueFlows JSON-LD must be lossless +- DSL concepts must map cleanly to Valueflows vocabulary +- Terminology should align with Valueflows documentation +- Export to standard Valueflows JSON-LD must be lossless ### 8.3 Holochain Integration @@ -483,6 +519,42 @@ update resources where type == Equipment { } ``` +### 9.7 Sources — (Planned — Augmented ValueFlows, WIP) + +> **Illustrative future syntax, not implemented.** This sketch shows how the DSL _might_ express `vf:Source` once the augmented-ValueFlows profile is adopted. It is included only to reserve syntactic space; it is **not** part of the MVP grammar. Authoritative modeling lives in [`source-valueflows-integration.md`](source-valueflows-integration.md). + +```vf +# Declare a generative Source (Layer 0 NDO extension) — PLANNED +source WatershedX { + type: Hydrological + property_regime: Nondominium + regime_state: Stressed + stewarded_by: [Alice, Bob] + # coupling to a downstream Source + yields: AquiferY +} + +# Draw yield from the Source via the planned `extract` action — PLANNED +event abstraction_042 { + action: extract + provider: WatershedX # a Source acts as flow endpoint + receiver: Alice + resource: FreshWater + quantity: 500 L + at: 2026-04-01T09:00:00 +} + +# Adaptive governance keyed to observed boundary events — PLANNED +governance { + adaptive rule WaterAbstractionLimit { + applies_to: WatershedX + when: regime_state == Stressed + max_extract_per_day: 1000 L + on_breach: tighten_and_notify_stewards + } +} +``` + _See technical specifications for additional syntax examples and edge cases._ --- @@ -505,7 +577,7 @@ _See technical specifications for additional syntax examples and edge cases._ **Duration**: 4-6 weeks -1. Full ValueFlows action support +1. Full Valueflows action support 2. Process and recipe definitions 3. Governance rule configuration 4. Import/export functionality @@ -530,11 +602,17 @@ _See technical specifications for additional syntax examples and edge cases._ 1. Additional compilation targets (GraphQL, visualization) 2. Community feedback integration -3. Coordination with ValueFlows community +3. Coordination with Valueflows community 4. Template library for common patterns **Deliverables**: Sustainable community-driven development +### Future / Deferred: Augmented ValueFlows (`vf:Source`) support + +**Status**: Not scheduled — gated on adoption of the augmented-ValueFlows profile. + +Support for the `Source` primitive (§6.1.7, §9.7) — `source` declarations, the `extract` action, coupling links, `Steward` roles, and adaptive governance blocks — is **explicitly out of scope** for Phases 1–4. It will be planned as a distinct, versioned language extension only after the augmented-ValueFlows design ([`source-valueflows-integration.md`](source-valueflows-integration.md)) is ratified and the corresponding Nondominium backend (`SourceProfile`, Source flow endpoints, `Steward` role) is implemented. The MVP grammar reserves room for it without committing to a timeline. + --- ## 11. Success Criteria @@ -548,7 +626,7 @@ _See technical specifications for additional syntax examples and edge cases._ | **Script Reviewability** | Comprehend 200-line script in < 5 minutes | User testing with experienced administrators | | **Error Resolution** | Fix common errors in < 2 minutes using error messages | Measure time-to-fix for typical errors | | **External Adoption** | 2+ organizations using DSL in production by Q2 2026 | Track adoption through GitHub issues and community | -| **Community Feedback** | 80%+ positive sentiment on ValueFlows design alignment | Survey ValueFlows community members | +| **Community Feedback** | 80%+ positive sentiment on Valueflows design alignment | Survey Valueflows community members | | **Parse Performance** | Parse 1000-entity script in < 1 second | Automated performance benchmarking | | **Validation Accuracy** | < 1% false positive rate in validation errors | Test suite with valid and invalid scripts | | **Documentation Coverage** | 100% of language constructs documented | Automated documentation completeness check | @@ -584,7 +662,7 @@ _See technical specifications for additional syntax examples and edge cases._ **Correctness**: -- [ ] All ValueFlows actions supported and tested +- [ ] All Valueflows actions supported and tested - [ ] Economic logic validation prevents invalid states - [ ] Governance rules enforce correctly - [ ] Round-trip export/import preserves data 100% @@ -613,9 +691,9 @@ _See technical specifications for additional syntax examples and edge cases._ ### 11.4 Ecosystem Integration Criteria -**ValueFlows Alignment**: +**Valueflows Alignment**: -- [ ] Terminology matches ValueFlows specification +- [ ] Terminology matches Valueflows specification - [ ] Export to JSON-LD is lossless - [ ] Community review validates design approach - [ ] Contribution guidelines for upstream inclusion @@ -659,7 +737,7 @@ _See technical specifications for additional syntax examples and edge cases._ **File Extension**: -- **Proposed**: `.vf` (short, memorable, indicates ValueFlows) +- **Proposed**: `.vf` (short, memorable, indicates Valueflows) - **Alternatives**: `.nondom` (project-specific), `.valueflows` (explicit but long) - **Decision Target**: Q1 2026, after MVP prototype testing @@ -685,16 +763,20 @@ _See technical specifications for additional syntax examples and edge cases._ ## 13. References -- **ValueFlows Specification:** https://www.valueflo.ws/ +- **Valueflows Specification (v1.0):** https://www.valueflo.ws/ - **Nondominium Repository:** https://github.com/sensorica/nondominium - **hREA Project:** https://github.com/h-REA/hREA - **REA Ontology:** https://wiki.p2pfoundation.net/Resource-Event-Agent_Model - **Holochain Documentation:** https://developer.holochain.org/ -- **Technical Specifications:** [ValueFlows DSL Technical Specifications](../specifications/valueflows-dsl-specs.md) +- **Technical Specifications:** [Valueflows DSL Technical Specifications](../specifications/valueflows-dsl-specs.md) +- **Augmented ValueFlows — Source integration (planned/WIP):** [`source-valueflows-integration.md`](source-valueflows-integration.md) +- **Source-NDO requirements (planned/WIP):** [`source-ndo-requirements.md`](source-ndo-requirements.md) --- -## Appendix A: ValueFlows Action Reference +## Appendix A: Valueflows Action Reference + +The following are **ValueFlows 1.0** actions supported by the MVP DSL. | Action | Effect on Resource | Typical Use | | ------------------- | ------------------------- | ------------------------- | @@ -717,6 +799,12 @@ _See technical specifications for additional syntax examples and edge cases._ | `lower` | Decrements (adjustment) | Inventory correction down | | `copy` | Creates duplicate | Digital resources | +**Planned — Augmented ValueFlows (not in MVP DSL):** + +| Action | Effect on Resource / Source | Typical Use | +| --------- | -------------------------------------- | ---------------------------------------------------- | +| `extract` | Draws yield from a `vf:Source`; debits the Source's stock/regime state | Abstracting water from a watershed; downloading a design from a knowledge commons | + --- ## Appendix B: Glossary @@ -724,6 +812,7 @@ _See technical specifications for additional syntax examples and edge cases._ | Term | Definition | | -------------------------- | -------------------------------------------------------------------------------------- | | **Agent** | A person, organization, or ecological entity that can participate in economic activity | +| **Augmented ValueFlows** | _(Planned/WIP)_ A proposed profile extending ValueFlows 1.0 with the `vf:Source` primitive, the `extract` action, and adaptive stewardship governance | | **Commitment** | A promise to perform an economic event in the future | | **DHT** | Distributed Hash Table — Holochain's data storage mechanism | | **Economic Event** | An observed change in resources or resource rights | @@ -735,5 +824,8 @@ _See technical specifications for additional syntax examples and edge cases._ | **Recipe** | A template defining a repeatable process | | **REA** | Resource-Event-Agent — An accounting ontology | | **Resource Specification** | A type or kind of resource (not an instance) | -| **ValueFlows** | A vocabulary for distributed economic coordination | +| **Source (`vf:Source`)** | _(Planned/WIP)_ A proposed third ValueFlows primitive: a generative, non-ownable, partially unknowable system that yields resources, receives effects, and conditions future possibilities (e.g. a watershed or knowledge commons) | +| **Source-NDO** | _(Planned/WIP)_ A Nondominium NDO whose Layer 0 carries a `SourceProfile`, representing a `vf:Source` in the hApp | +| **Steward** | _(Planned/WIP)_ A functional role for Source governance, emphasizing obligations toward a Source over rights over a resource | +| **Valueflows** | A vocabulary for distributed economic coordination (this DSL targets v1.0) | | **Zome** | A module in a Holochain application | From a1af047e174177844e6ff5a7e81189db2e592c90 Mon Sep 17 00:00:00 2001 From: Tiberius Brastaviceanu Date: Thu, 6 Aug 2026 15:16:52 -0400 Subject: [PATCH 04/18] feat(resource): introduce OperationalState enum for EconomicResource management Added the OperationalState enum to represent the current process condition of EconomicResource instances, allowing for states such as Available, Reserved, InTransit, InStorage, InMaintenance, InUse, and PendingValidation. Implemented functionality for creating, updating, and querying resources by their operational state. Updated relevant tests and documentation to reflect these changes, enhancing the resource management capabilities within the Nondominium architecture. --- crates/shared/src/types.rs | 29 ++ dnas/nondominium/tests/src/resource/mod.rs | 148 ++++++++ .../zome_resource/src/economic_resource.rs | 110 +++++- .../zomes/integrity/zome_resource/src/lib.rs | 57 +-- documentation/API_REFERENCE.md | 21 +- documentation/ARCHITECTURE_COMPONENTS.md | 3 +- documentation/DOCUMENTATION_INDEX.md | 4 +- documentation/IMPLEMENTATION_STATUS.md | 286 +++++++++++---- documentation/hREA/integration-strategy.md | 2 +- documentation/implementation_plan.md | 345 ++++++++++++------ .../requirements/ndo_prima_materia.md | 43 ++- documentation/requirements/requirements.md | 184 +++++++++- documentation/requirements/resources.md | 27 +- .../specifications/VfAction_Usage.md | 8 +- .../governance/cross-zome-api.md | 16 +- .../governance-operator-architecture.md | 4 +- ...overnance-operator-implementation-guide.md | 21 +- .../ndo-v1-architecture-design.md | 2 +- .../protocol-bridge-specifications.md | 3 +- documentation/zomes/architecture_overview.md | 3 +- documentation/zomes/resource_zome.md | 77 ++-- packages/shared-types/src/resource.types.ts | 23 +- pai/cursor-rules/10-domain-enums.md | 7 +- tests/src/nondominium/resource/common.ts | 30 +- .../resource-foundation-tests.test.ts | 6 +- .../resource-integration-tests.test.ts | 4 +- .../resource/resource-scenario-tests.test.ts | 30 +- .../resource/resource-update-test.test.ts | 6 +- ui/src/lib/components/ndo/ResourcesTab.svelte | 5 +- ui/src/lib/errors/error-contexts.ts | 4 +- ui/src/lib/schemas/resource.schemas.ts | 18 +- ui/src/lib/services/zomes/resource.service.ts | 26 +- ui/src/lib/utils/holochain-records.ts | 2 +- ui/src/lib/utils/operational-state-labels.ts | 19 + 34 files changed, 1120 insertions(+), 453 deletions(-) create mode 100644 ui/src/lib/utils/operational-state-labels.ts diff --git a/crates/shared/src/types.rs b/crates/shared/src/types.rs index 52dd2de..1ed461c 100644 --- a/crates/shared/src/types.rs +++ b/crates/shared/src/types.rs @@ -64,6 +64,35 @@ pub enum ResourceNature { Information, } +/// Current process condition on a specific EconomicResource instance (Layer 2). +/// Cycles frequently as processes begin and end; orthogonal to LifecycleStage. +#[derive(Clone, PartialEq, Debug, Serialize, Deserialize, Default)] +pub enum OperationalState { + Available, + Reserved, + InTransit, + InStorage, + InMaintenance, + InUse, + #[default] + PendingValidation, +} + +impl std::fmt::Display for OperationalState { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let s = match self { + OperationalState::Available => "available", + OperationalState::Reserved => "reserved", + OperationalState::InTransit => "in_transit", + OperationalState::InStorage => "in_storage", + OperationalState::InMaintenance => "in_maintenance", + OperationalState::InUse => "in_use", + OperationalState::PendingValidation => "pending_validation", + }; + write!(f, "{}", s) + } +} + // ─── ValueFlows action enum ─────────────────────────────────────────────────── // Shared here so ValidateContributionInput (io/governance.rs) can reference it // without needing to import from the governance integrity zome (a WASM crate). diff --git a/dnas/nondominium/tests/src/resource/mod.rs b/dnas/nondominium/tests/src/resource/mod.rs index ec71d7e..6a2aa81 100644 --- a/dnas/nondominium/tests/src/resource/mod.rs +++ b/dnas/nondominium/tests/src/resource/mod.rs @@ -4,6 +4,9 @@ //! `action_hashes` field is returned in parallel with `specifications` and //! that both vectors have the same length and order. //! +//! Covers `OperationalState` on `EconomicResource`: default on create, +//! `update_operational_state`, and `get_resources_by_operational_state`. +//! //! Prerequisites (runtime — not compile-time): //! bun run build:happ # builds nondominium.dna //! @@ -11,6 +14,7 @@ //! CARGO_TARGET_DIR=target/native-tests cargo test --test resource use holochain::prelude::*; +use nondominium_shared::types::OperationalState; use serde::{Deserialize, Serialize}; use nondominium_sweettest::common::*; @@ -60,6 +64,44 @@ struct GetAllResourceSpecificationsOutput { pub action_hashes: Vec, } +#[derive(Debug, Serialize, Deserialize)] +struct EconomicResourceInput { + pub spec_hash: ActionHash, + pub quantity: f64, + pub unit: String, + pub current_location: Option, +} + +#[derive(Debug, Serialize, Deserialize)] +struct EconomicResource { + pub quantity: f64, + pub unit: String, + pub custodian: AgentPubKey, + pub current_location: Option, + pub operational_state: OperationalState, +} + +#[derive(Debug, Serialize, Deserialize)] +struct CreateEconomicResourceOutput { + pub resource_hash: ActionHash, + pub resource: EconomicResource, +} + +#[derive(Debug, Serialize, Deserialize)] +struct UpdateOperationalStateInput { + pub resource_hash: ActionHash, + pub new_operational_state: OperationalState, +} + +fn decode_record_entry(record: &Record) -> T { + match record.entry().as_option() { + Some(Entry::App(app_bytes)) => { + holochain_serialized_bytes::decode(app_bytes.bytes()).expect("entry deserialization failed") + } + _ => panic!("expected Present App entry"), + } +} + // --------------------------------------------------------------------------- // Tests // --------------------------------------------------------------------------- @@ -135,3 +177,109 @@ async fn get_all_resource_specifications_returns_parallel_hashes() { ); } } + +/// New economic resources default to `PendingValidation`; custodian can update +/// operational state and query by operational state anchor. +#[tokio::test(flavor = "multi_thread")] +async fn economic_resource_operational_state_lifecycle() { + let (conductors, alice, _bob) = setup_two_agents().await; + + let spec_input = ResourceSpecificationInput { + name: "Operational Drill".to_string(), + description: "Cordless drill for shared use".to_string(), + category: "tools".to_string(), + image_url: None, + tags: vec!["tools".to_string()], + governance_rules: vec![], + }; + + let spec_out: CreateResourceSpecificationOutput = conductors[0] + .call( + &alice.zome("zome_resource"), + "create_resource_specification", + spec_input, + ) + .await; + + let resource_input = EconomicResourceInput { + spec_hash: spec_out.spec_hash.clone(), + quantity: 1.0, + unit: "piece".to_string(), + current_location: Some("Workshop".to_string()), + }; + + let create_out: CreateEconomicResourceOutput = conductors[0] + .call( + &alice.zome("zome_resource"), + "create_economic_resource", + resource_input, + ) + .await; + + assert_eq!( + create_out.resource.operational_state, + OperationalState::PendingValidation, + "new instances must start PendingValidation" + ); + + let pending_records: Vec = conductors[0] + .call( + &alice.zome("zome_resource"), + "get_resources_by_operational_state", + OperationalState::PendingValidation, + ) + .await; + + assert!( + pending_records.iter().any(|r| { + decode_record_entry::(r).operational_state + == OperationalState::PendingValidation + }), + "PendingValidation query should include the new resource" + ); + + let updated: Record = conductors[0] + .call( + &alice.zome("zome_resource"), + "update_operational_state", + UpdateOperationalStateInput { + resource_hash: create_out.resource_hash.clone(), + new_operational_state: OperationalState::InUse, + }, + ) + .await; + + let updated_resource: EconomicResource = decode_record_entry(&updated); + assert_eq!( + updated_resource.operational_state, + OperationalState::InUse, + "operational state should update to InUse" + ); + + let in_use_records: Vec = conductors[0] + .call( + &alice.zome("zome_resource"), + "get_resources_by_operational_state", + OperationalState::InUse, + ) + .await; + + assert_eq!( + in_use_records.len(), + 1, + "exactly one resource should be InUse after update" + ); + + let pending_after: Vec = conductors[0] + .call( + &alice.zome("zome_resource"), + "get_resources_by_operational_state", + OperationalState::PendingValidation, + ) + .await; + + assert!( + pending_after.is_empty(), + "PendingValidation anchor should no longer list the resource" + ); +} diff --git a/dnas/nondominium/zomes/coordinator/zome_resource/src/economic_resource.rs b/dnas/nondominium/zomes/coordinator/zome_resource/src/economic_resource.rs index 71351e4..2a13136 100644 --- a/dnas/nondominium/zomes/coordinator/zome_resource/src/economic_resource.rs +++ b/dnas/nondominium/zomes/coordinator/zome_resource/src/economic_resource.rs @@ -2,6 +2,58 @@ use crate::ResourceError; use hdk::prelude::*; use zome_resource_integrity::*; +fn operational_state_path(state: &OperationalState) -> ExternResult { + Path::from(format!("ndo.opstate.{:?}", state)).path_entry_hash() +} + +/// Walk the EconomicResource update chain to the root (create) action hash. +fn root_economic_resource_action_hash(mut hash: ActionHash) -> ExternResult { + loop { + let record = must_get_valid_record(hash.clone())?; + match record.action() { + Action::Update(update) => { + hash = update.original_action_address.clone(); + } + _ => return Ok(hash), + } + } +} + +fn move_operational_state_link( + original_action_hash: &ActionHash, + old_state: &OperationalState, + new_state: &OperationalState, +) -> ExternResult<()> { + if old_state == new_state { + return Ok(()); + } + + let old_links = get_links( + LinkQuery::try_new( + operational_state_path(old_state)?, + LinkTypes::ResourcesByOperationalState, + )?, + GetStrategy::default(), + )?; + for link in old_links { + if let Some(target_hash) = link.target.into_action_hash() { + if target_hash == *original_action_hash { + delete_link(link.create_link_hash, GetOptions::default())?; + break; + } + } + } + + create_link( + operational_state_path(new_state)?, + original_action_hash.clone(), + LinkTypes::ResourcesByOperationalState, + (), + )?; + + Ok(()) +} + // Cross-zome call structure for governance validation #[derive(Serialize, Deserialize, Debug)] pub struct ValidateNewResourceInput { @@ -50,7 +102,7 @@ pub fn create_economic_resource( unit: input.unit, custodian: agent_info.agent_initial_pubkey.clone(), current_location: input.current_location, - state: ResourceState::PendingValidation, // New resources start in pending validation state + operational_state: OperationalState::PendingValidation, }; let resource_hash = create_entry(&EntryTypes::EconomicResource(resource.clone()))?; @@ -64,6 +116,13 @@ pub fn create_economic_resource( (), )?; + create_link( + operational_state_path(&OperationalState::PendingValidation)?, + resource_hash.clone(), + LinkTypes::ResourcesByOperationalState, + (), + )?; + // Link resource to its specification create_link( input.spec_hash.clone(), @@ -197,7 +256,7 @@ pub fn update_economic_resource(input: UpdateEconomicResourceInput) -> ExternRes unit: input.updated_resource.unit, custodian: original_resource.custodian, // Keep the same custodian current_location: input.updated_resource.current_location, - state: original_resource.state, // Keep the same state unless explicitly changed + operational_state: original_resource.operational_state, }; let updated_resource_hash = update_entry(input.previous_action_hash, &updated_resource)?; @@ -439,13 +498,13 @@ pub fn transfer_custody(input: TransferCustodyInput) -> ExternResult ExternResult { +pub fn update_operational_state(input: UpdateOperationalStateInput) -> ExternResult { let agent_info = agent_info()?; // Get the current resource @@ -466,8 +525,11 @@ pub fn update_resource_state(input: UpdateResourceStateInput) -> ExternResult ExternResult ExternResult ExternResult ExternResult> { + let links = get_links( + LinkQuery::try_new( + operational_state_path(&state)?, + LinkTypes::ResourcesByOperationalState, + )?, + GetStrategy::default(), + )?; + + let mut records = Vec::new(); + for link in links { + if let Some(original_hash) = link.target.into_action_hash() { + if let Ok(Some(record)) = get_latest_economic_resource_record(original_hash) { + records.push(record); + } + } + } + + Ok(records) +} diff --git a/dnas/nondominium/zomes/integrity/zome_resource/src/lib.rs b/dnas/nondominium/zomes/integrity/zome_resource/src/lib.rs index 1d321b8..b1c95b2 100644 --- a/dnas/nondominium/zomes/integrity/zome_resource/src/lib.rs +++ b/dnas/nondominium/zomes/integrity/zome_resource/src/lib.rs @@ -1,42 +1,10 @@ use hdi::prelude::*; -pub use nondominium_shared::types::{LifecycleStage, PropertyRegime, ResourceNature}; +pub use nondominium_shared::types::{ + LifecycleStage, OperationalState, PropertyRegime, ResourceNature, +}; -// TODO (post-MVP): Split ResourceState into two orthogonal enums and migrate EconomicResource: -// -// 1. LifecycleStage — now in nondominium_shared::types (imported above). -// -// 2. OperationalState — the current process acting on this specific resource instance (cycles -// frequently as processes begin and end). Governance-zome controlled. -// Values: Available, Reserved, InTransit, InStorage, InMaintenance, InUse, PendingValidation -// -// The current ResourceState enum CONFLATES both dimensions and is kept for EconomicResource -// backwards-compatibility until the OperationalState refactor (REQ-NDO-OS-06). -// -// See: documentation/requirements/ndo_prima_materia.md — Section 5 (LifecycleStage + OperationalState) -// See: documentation/archives/resources.md — Section 2.4 (known gaps) -#[derive(Clone, PartialEq, Debug, Serialize, Deserialize, Default)] -pub enum ResourceState { - #[default] - PendingValidation, - Active, - Maintenance, - Retired, - Reserved, -} - -impl std::fmt::Display for ResourceState { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - ResourceState::PendingValidation => write!(f, "pending_validation"), - ResourceState::Active => write!(f, "active"), - ResourceState::Maintenance => write!(f, "maintenance"), - ResourceState::Retired => write!(f, "retired"), - ResourceState::Reserved => write!(f, "reserved"), - } - } -} - -// LifecycleStage, PropertyRegime, ResourceNature are re-exported from nondominium_shared::types +// LifecycleStage, PropertyRegime, ResourceNature, OperationalState are re-exported from +// nondominium_shared::types // (see the `pub use` at the top of this file). Both DNAs share the same definitions, eliminating // the duplication that previously existed between this file and zome_lobby_integrity. @@ -66,7 +34,7 @@ pub struct EconomicResource { pub unit: String, pub custodian: AgentPubKey, // The Primary Accountable Agent holding the resource pub current_location: Option, // Physical or virtual location TODO: use an enum - pub state: ResourceState, + pub operational_state: OperationalState, } // NDO Layer 0 — NondominiumIdentity (REQ-NDO-L0-01, REQ-NDO-L0-07) @@ -158,11 +126,8 @@ pub enum LinkTypes { // Service-type patterns (inspired by R&O ServiceType queries) SpecsByCategory, // Category -> ResourceSpecs ResourcesByLocation, // Location -> EconomicResources - ResourcesByState, // ResourceState -> EconomicResources - // TODO (REQ-NDO-OS-06): Split ResourcesByState into two independent link types: - // ResourcesByLifecycleStage — NondominiumIdentity lifecycle facet queries - // ResourcesByOperationalState — EconomicResource operational facet queries - // See: documentation/requirements/ndo_prima_materia.md — Section 9.4 (REQ-NDO-OS-06) + // Lifecycle faceting for NDO identity is served by NdoByLifecycleStage (Layer 0). + ResourcesByOperationalState, // OperationalState -> EconomicResource action hashes // Governance patterns RulesByType, // RuleType -> GovernanceRules @@ -327,6 +292,12 @@ fn validate_create_economic_resource( )); } + if resource.operational_state != OperationalState::PendingValidation { + return Ok(ValidateCallbackResult::Invalid( + "New economic resources must start in PendingValidation operational state".to_string(), + )); + } + Ok(ValidateCallbackResult::Valid) } diff --git a/documentation/API_REFERENCE.md b/documentation/API_REFERENCE.md index 14b787e..a47ea20 100644 --- a/documentation/API_REFERENCE.md +++ b/documentation/API_REFERENCE.md @@ -763,21 +763,22 @@ pub struct UpdateEconomicResourceInput { **Authorization**: Public access **Returns**: Resources where agent has accountability or custody -#### `update_resource_state(input: UpdateResourceStateInput) -> ExternResult` -**Purpose**: Update resource state with validation -**Authorization**: Primary accountable agent or authorized role +#### `update_operational_state(input: UpdateOperationalStateInput) -> ExternResult` +**Purpose**: Update `EconomicResource.operational_state` (REQ-NDO-OS-01) +**Authorization**: Current agent (interim; governance-zome ownership deferred per REQ-NDO-OS-02) **Input**: ```rust -pub struct UpdateResourceStateInput { +pub struct UpdateOperationalStateInput { pub resource_hash: ActionHash, - pub new_state: String, - pub stage: Option, - pub location: Option, - pub note: Option, + pub new_operational_state: OperationalState, } ``` -**Returns**: State update record with economic event -**Validation**: State transitions validated against specification rules +**Returns**: Updated `EconomicResource` record; moves `ResourcesByOperationalState` anchor link + +#### `get_resources_by_operational_state(state: OperationalState) -> ExternResult>` +**Purpose**: Faceted discovery of economic resources by operational state (REQ-NDO-OS-06) +**Authorization**: Public read +**Returns**: Records linked from `ndo.opstate.{state}` anchor --- diff --git a/documentation/ARCHITECTURE_COMPONENTS.md b/documentation/ARCHITECTURE_COMPONENTS.md index 989f563..373b622 100644 --- a/documentation/ARCHITECTURE_COMPONENTS.md +++ b/documentation/ARCHITECTURE_COMPONENTS.md @@ -233,7 +233,7 @@ graph TB subgraph "Economic Resource" EconRes[EconomicResource
Resource Instance] - ResState[LifecycleStage + OperationalState
State Tracking (TODO: split ResourceState)] + ResState[LifecycleStage on NDO + OperationalState on EconomicResource] ResHistory[ResourceHistory
Audit Trail] ResCustody[ResourceCustody
Custody Tracking] end @@ -282,7 +282,6 @@ graph TB │ 2.2 ECONOMIC RESOURCE │ │ ├── EconomicResource Entry (resource instance) │ │ ├── LifecycleStage (on NondominiumIdentity) + OperationalState (on EconomicResource) │ -│ │ TODO: split current ResourceState into these two enums │ │ ├── ResourceHistory Entry (audit trail) │ │ └── ResourceCustody Entry (custody tracking) │ │ │ diff --git a/documentation/DOCUMENTATION_INDEX.md b/documentation/DOCUMENTATION_INDEX.md index 1589837..8396be6 100644 --- a/documentation/DOCUMENTATION_INDEX.md +++ b/documentation/DOCUMENTATION_INDEX.md @@ -228,10 +228,10 @@ Full reference: **[API Reference](API_REFERENCE.md)** - `create_economic_resource()` - Create resource instances with initial state - `get_economic_resource()` - Retrieve resource current state and history - `get_economic_resource_with_state()` - Retrieve resource with full state transitions -- `update_economic_resource_state()` - Update resource state (requires governance approval) +- `update_operational_state()` - Update `EconomicResource.operational_state` - `get_my_resources()` - Discover resources where calling agent is custodian - `get_resources_by_specification()` - Find resources conforming to specification -- `get_resources_by_state()` - Query resources by current state +- `get_resources_by_operational_state()` - Query resources by operational state **Cross-Zome State Transitions** diff --git a/documentation/IMPLEMENTATION_STATUS.md b/documentation/IMPLEMENTATION_STATUS.md index e89f830..4a9b68f 100644 --- a/documentation/IMPLEMENTATION_STATUS.md +++ b/documentation/IMPLEMENTATION_STATUS.md @@ -15,40 +15,63 @@ This document tracks what is **actually implemented and verified** in the curren - **Testing**: Sweettest (Rust, primary) — Tryorama (TypeScript) is deprecated - **Client**: @holochain/client 0.19.0 for DHT interaction -### Zome Architecture (3-Zome Structure) +### Multi-DNA hApp Architecture -1. **`zome_person`** - Agent identity, profiles, roles, and capability-based access control -2. **`zome_resource`** - Resource specifications, lifecycle management, and governance rules -3. **`zome_gouvernance`** - Economic events, commitments, claims, and the PPR reputation system +The packaged hApp currently contains four roles: -Each zome follows the integrity/coordinator pattern. +1. **`lobby`** — fixed, permissionless federation DHT for Lobby profiles and Group discovery +2. **`nondominium`** — the core NDO DNA, containing: + - `zome_person` — Agent identity, profiles, roles, capabilities, and devices + - `zome_resource` — specifications, inventoried resources, governance-rule data, and NDO Layer 0 + - `zome_gouvernance` — events, commitments, claims, validation, PPR prototypes, and federation extensions +3. **`hrea`** — bundled hREA DNA used by the Person/ReaAgent bridge +4. **`group`** — deferred template role; each Group is provisioned as an isolated cloned cell (`clone_limit: 64`) + +Each local DNA domain follows the integrity/coordinator pattern. The core Nondominium domain remains a three-zome architecture, but the installed hApp is a multi-DNA system. + +### Status Terminology + +- **Complete** — implemented end-to-end for the stated scope and covered by active tests +- **Implemented** — working code/API exists, but may not be exposed in every UI +- **Partial / prototype** — code exists, but contains placeholders, incomplete workflow integration, or limited tests +- **Not implemented** — no operational implementation exists --- -## Phase 1: Complete ✅ +## Core Backend -### Person Management +### Person Management 🔄 Core implemented; workflows partial - **Public Profiles**: `Person` entries with name, avatar, and bio -- **Private Data**: `EncryptedProfile` entries with PII (legal name, email, phone, address, emergency contact) +- **Private Data**: private `PrivatePersonData` entries with legal name, email, phone, address, emergency contact, time zone, and location - **Role-Based Access**: `PersonRole` assignments — `SimpleAgent`, `AccountableAgent`, `PrimaryAccountableAgent`, `Transport`, `Repair`, `Storage` -- **Agent-to-Person Mapping**: Secure linking between Holochain agents and their profiles +- **Agent-to-Person Mapping**: bidirectional Agent↔Person links supporting multiple agent keys per Person +- **Profile APIs**: create, update, latest-version resolution, global discovery, current-agent profile, and composed Person profile queries -#### Capability-Based Access Control ✅ +#### Capability-Based Access Control 🔄 Prototype -- **Capability Grants**: Time-limited access tokens with field-level permissions -- **Filtered Data Access**: `FilteredPrivateData` entries with selective field exposure -- **Grant Metadata**: `PrivateDataCapabilityMetadata` for tracking access grants +- **Capability Grants**: Holochain capability grants plus `PrivateDataCapabilityMetadata` with field-level allowlists, context, expiry, and local capability secret +- **Filtered Data Access**: `FilteredPrivateData` response views - **Field-Level Control**: Granular permissions for email, phone, location, time_zone, emergency_contact, address -- **Time-Based Expiration**: 30-day maximum grant duration with configurable expiration +- **Time-Based Expiration**: callable grants accept arbitrary `expires_in_days` (default 7); role-based defaults top out at 30 days, but there is **no global hard maximum enforcement** +- **Implemented APIs**: `grant_private_data_access`, `create_private_data_cap_claim`, `get_private_data_with_capability`, `revoke_private_data_access`, owned/role-based/transferable grant helpers, and governance-oriented private-data validation +- **Prototype limitations**: retrieval still contains mock/fallback paths for test situations, and comprehensive active Sweettests are missing + +#### Multi-Device Support ✅ Implemented + +- `Device` entries with `Active`, `Inactive`, and `Revoked` status +- `AgentPersonRelationship` entries with `Primary`, `Secondary`, and `Device` relationship types +- Device registration, per-Person and current-agent discovery, device lookup, activity updates, and deactivation +- Device and relationship integrity validation and bidirectional Person/device links -#### Not yet implemented (person domain) +#### Partial or not yet implemented (person domain) - Private data access request/approval workflow (#40) - Audit trail for private data access events (#38) - `get_expiring_grants()` for proactive grant lifecycle management (#37) -- Full agent promotion workflow logic (#33) — roles exist, promotion workflow incomplete -- Specialized role validation (#34) +- Full agent promotion workflow (#33): promotion and approval externs exist, but `request_role_promotion` still returns a placeholder hash instead of a queryable request entry +- Specialized role validation (#34): the governance extern exists but currently auto-approves and contains Phase 2 authorization/credential TODOs +- Complete active Sweettest coverage for capability sharing, roles, devices, and promotion workflows ### Resource Management @@ -57,30 +80,34 @@ Each zome follows the integrity/coordinator pattern. - `ResourceSpecification` entries with name, description, category - Tag-based discovery, governance rule linking, active/inactive status -#### Economic Resources ✅ +#### Economic Resources ✅ Data model and CRUD implemented - `EconomicResource` entries conforming to specifications - Quantity tracking with units, custodian assignment, location metadata -- Five-state lifecycle: `PendingValidation`, `Active`, `Maintenance`, `Retired`, `Reserved` +- `OperationalState` on `EconomicResource`: `PendingValidation`, `Available`, `Reserved`, `InTransit`, `InStorage`, `InMaintenance`, `InUse` (REQ-NDO-OS-01 ✅ data layer) +- Creation, updates, latest-version resolution, queries by specification/custodian/operational state, first-resource checks, custody transfer, and `update_operational_state` / `get_resources_by_operational_state` APIs -> **Note**: The current `ResourceState` conflates lifecycle maturity and operational condition. The NDO three-layer model (post-MVP) separates these into `LifecycleStage` + `OperationalState`. See `documentation/requirements/ndo_prima_materia.md`. +> **Note**: Lifecycle maturity lives on `NondominiumIdentity` (`LifecycleStage`). Process condition lives on `EconomicResource` (`operational_state`). Governance-zome ownership of operational transitions (REQ-NDO-OS-02/03) remains deferred. -#### Governance Rules ✅ +#### Governance Rules 🔄 Persistence implemented; enforcement pending -- Extensible rule system with JSON-encoded parameters -- Enforcement role requirements, resource attachment, audit trail +- `GovernanceRule` CRUD, update chains, type discovery, and specification attachment +- Extensible `rule_type`, JSON-encoded `rule_data`, and optional `enforced_by` role metadata +- Rule semantics are not yet evaluated programmatically; update integrity validation remains permissive pending Governance-as-Operator #### NDO Layer 0 — Identity Anchor ✅ `NondominiumIdentity` provides a permanent identity anchor for any resource from conception through end-of-life. Implemented in PR #80. -- **Entry type**: `NondominiumIdentity` with `name`, `initiator`, `property_regime`, `resource_nature`, `lifecycle_stage`, `created_at`, `description`, `successor_ndo_hash` -- **Enums**: `LifecycleStage` (10 stages: Ideation→Specification→Development→Prototype→Stable→Distributed→Active→Hibernating→Deprecated→EndOfLife), `PropertyRegime` (4 variants: Private, Commons, Nondominium, CommonPool — Collective and Pool removed after design review), `ResourceNature` (5 variants: Physical, Digital, Service, Hybrid, Information — extends spec's 3-variant definition with Service and Information) -- **Immutability**: Only `lifecycle_stage` may change post-creation; `successor_ndo_hash` set exactly once on Deprecated transition; deletes are always invalid +- **Entry type**: `NondominiumIdentity` with `name`, `initiator`, `property_regime`, `resource_nature`, `lifecycle_stage`, `created_at`, `description`, `successor_ndo_hash`, and `hibernation_origin` +- **LifecycleStage**: 10 stages — Ideation → Specification → Development → Prototype → Stable → Distributed → Active → Hibernating → Deprecated → EndOfLife +- **PropertyRegime**: 6 canonical variants — `Private`, `Commons`, `Collective`, `Pool`, `CommonPool`, `Nondominium` +- **ResourceNature**: 5 variants — `Physical`, `Digital`, `Service`, `Hybrid`, `Information` +- **Immutability**: identity fields are permanent; `lifecycle_stage` changes through the validated state machine, `successor_ndo_hash` is set once on deprecation, and `hibernation_origin` is set/cleared during suspension/resumption; deletes are always invalid - **Authorization**: Only the `initiator` may call `update_lifecycle_stage` (MVP simplification; full role-based authorization per REQ-NDO-LC-07 deferred to governance zome integration) - **Discovery links**: `AllNdos` (global `"ndo_identities"` path anchor), `AgentToNdo` (per-initiator), `NdoByLifecycleStage` / `NdoByNature` / `NdoByPropertyRegime` (categorization anchors — PR #84) - **API**: `create_ndo`, `get_ndo` (resolves update chain), `get_all_ndos` (global anchor traversal), `get_my_ndos` (resolved entries), `update_lifecycle_stage`, `get_ndos_by_lifecycle_stage`, `get_ndos_by_nature`, `get_ndos_by_property_regime` (PR #84) -- **REQ coverage**: REQ-NDO-L0-01, -02, -03, -04, -06, -07 implemented; not yet enforced: REQ-NDO-L0-05 (EconomicEvent ref on transitions, optional in coordinator), REQ-NDO-LC-02 (governance-as-operator for transition validation), REQ-NDO-LC-03 (automatic EconomicEvent generation per transition), REQ-NDO-LC-05 (EndOfLife challenge period), REQ-NDO-LC-07 (role-based authorization per §5.3) +- **REQ coverage**: Layer 0 creation, permanence, lifecycle validation, and facet links are implemented. Link-level integrity hardening remains pending for categorization links. Also pending: required transition EconomicEvents, Governance-as-Operator evaluation, automatic event generation, EndOfLife challenge periods, and role-based lifecycle authorization. ### Discovery and Query Patterns ✅ @@ -90,7 +117,7 @@ Each zome follows the integrity/coordinator pattern. --- -## Phase 2: In Progress 🔄 +## ValueFlows and Governance Backend ### ValueFlows Economic Framework @@ -98,19 +125,21 @@ Each zome follows the integrity/coordinator pattern. Standard ValueFlows actions (`Transfer`, `Move`, `Use`, `Consume`, `Produce`, `Work`, `Modify`, `Combine`, `Separate`, `Raise`, `Lower`, `Cite`, `Accept`) plus nondominium extensions (`InitialTransfer`, `AccessForUse`, `TransferCustody`). -#### Economic Events ✅ +#### Economic Events ✅ Entry/API implemented -- `EconomicEvent` entry capture with provider/receiver, resource linking, quantity, timestamping +- `EconomicEvent` creation and retrieval with provider/receiver, resource references, quantity, timestamp, and optional note +- Queries by Agent and EconomicResource -#### Commitments & Claims ✅ +#### Commitments & Claims ✅ Entry/API implemented - Future economic commitments with due dates - `Claim` entries for fulfillment tracking -- Bidirectional links: Commitments ↔ Events ↔ Claims +- Commitment proposal/acceptance and Claim creation/retrieval APIs +- Links from Agents/resources to Commitments and from Commitments to Claims -#### Economic Processes ❌ Not implemented +#### Economic Processes ❌ Not implemented end-to-end -Use, Transport, Storage, and Repair process workflows are specified but not implemented. Tracked in #28, #29, #31, #32. +Use, Transport, Storage, and Repair process workflows are specified but not implemented as `EconomicProcess` entries or coordinated state machines. Existing VfAction, Commitment, EconomicEvent, resource transition, and WorkLog primitives do not yet form these workflows. Tracked in #28, #29, #31, #32. ### PPR Reputation System @@ -126,26 +155,78 @@ Use, Transport, Storage, and Repair process workflows are specified but not impl Performance score fields (timeliness, quality, reliability, communication, satisfaction) and `ReputationSummary` struct with category breakdowns are implemented. -#### Cryptographic Authentication ✅ +#### Cryptographic Authentication 🔄 Prototype -Bilateral signature system with dual signatures, hash-based security, and temporal validation is implemented in the integrity zome. +Signature structures, signed-data hashing, timestamp checks, score-range validation, and signer checks exist. However, `issue_participation_receipts` currently inserts a placeholder counterparty signature. The counterparty must subsequently call `sign_participation_claim`; this is not yet a fully authenticated, atomic bilateral issuance flow. + +#### Implemented PPR coordinator surface 🔄 + +- `issue_participation_receipts` +- `sign_participation_claim` +- `validate_participation_claim_signature` +- `validate_participation_claim_signature_enhanced` +- `get_my_participation_claims` +- `derive_reputation_summary` + +These are operational prototypes. Claim discovery uses DHT links (`AgentToPrivateParticipationClaims` and related links), despite the broader design goal that PPRs remain private and unlinked. `derive_reputation_summary` summarizes only the calling agent's local linked receipts. #### Not yet implemented (PPR domain) -- Bi-directional receipt generation zome functions (#14) -- Genesis role and custody receipt issuance workflows (#15, #16) +- Fully authenticated bilateral issuance without placeholder signatures (#14) +- Privacy-preserving storage without DHT discovery links to private claim action hashes +- Automatic guaranteed PPR issuance for every Commitment→EconomicEvent→Claim cycle +- Complete genesis role and custody receipt workflows (#15, #16) - End-of-life management with multi-validator security (#18) - Challenge period mechanism for EOL declarations (#19) - Historical review system for EOL abuse prevention (#20) -- PPR reputation aggregation zome function (#21) +- Production-grade reputation sharing/verification workflow; the local `derive_reputation_summary` function exists, but portable or third-party-verifiable summaries do not + +### Governance and Validation 🔄 Partial + +- `ValidationReceipt` and `ResourceValidation` entry types +- Resource, process-event, process-completion, agent-identity, and specialized-role validation externs +- Multi-reviewer status tracking and validation history queries +- Person↔governance private-data validation helpers + +Several checks are still simplified or stubbed: specialized-role validation auto-approves, authorization is incomplete in places, GovernanceRule semantics are not evaluated, and event/PPR generation is not uniformly automatic. + +### Governance-as-Operator Architecture ❌ Specified, not implemented + +The Request→Evaluate→Apply architecture is documented in `documentation/specifications/governance/`, but the Rust DNA does **not** currently define `GovernanceTransitionRequest`, `TransitionContext`, `GovernanceTransitionResult`, `evaluate_state_transition`, `evaluate_governance_transition`, or `request_resource_transition`. Existing validation and private-data helpers are related infrastructure, not that operator path. Tracked in #41–#44. + +--- + +## Lobby DNA ✅ Implemented + +### Purpose and Data Model + +The Lobby is a fixed, permissionless DHT used as the federation entry point. It does not store NDO announcements directly. + +- `LobbyAgentProfile` — `handle`, optional `avatar_url`, optional `bio`, `lobby_pubkey`, and `created_at` +- `GroupAnnouncement` — `group_name`, `group_dna_hash`, `network_seed`, optional `description`, and `registered_by` (no stored announcement timestamp) +- Discovery/update links: `AllLobbyAgents`, `AgentToLobbyProfile`, `AgentProfileUpdates`, `AllGroupAnnouncements`, and `AgentToGroupAnnouncements` +- `get_group_announcement_by_dna_hash` scans the global announcement anchor; there is no dedicated DNA-hash→announcement link type -### Governance-as-Operator Architecture ❌ Not implemented +### Coordinator API (9 externs) -The governance-as-operator pattern (pure-function `GovernanceEngine`, cross-zome interface types, Request-Evaluate-Apply resource refactor, automatic event generation on state transitions) is fully specified in `documentation/specifications/governance/` but not yet implemented. Tracked in #41–#44. +`init`, `upsert_lobby_agent_profile`, `get_lobby_agent_profile`, `get_all_lobby_agents`, `announce_group`, `get_all_group_announcements`, `get_my_group_announcements`, `get_group_announcement_by_dna_hash`, `get_my_groups` + +`get_my_groups` is a lightweight Lobby-side descriptor query over announcements. In the frontend, `LobbyService.getMyGroups()` instead enumerates the conductor's Group clone cells and calls each cell's `get_my_group`, because local clone-cell installation is the authoritative source for Groups the current agent has joined. + +### Sweettest Coverage + +5 active scenarios in `dnas/lobby/tests/src/lobby/mod.rs`, covering profile create/update/discovery and Group announcement discovery/deduplication behavior. + +### Packaging + +- `lobby` role in `workdir/happ.yaml` +- Lobby integrity/coordinator WASM included in the hApp build +- Separate `lobby_sweettest` package +- Moss applet metadata in `workdir/moss.yaml` --- -## Group DNA ✅ Complete (PR #107) +## Group DNA ✅ Backend complete for current scope (PR #107) ### DNA Architecture @@ -153,14 +234,16 @@ Group cells use the **cloned-cell pattern**: a single Group DNA template is inst ### Entry Types -- `GroupProfile` — group name, description, initiator, created_at; one per cloned cell; anchor at `all_groups` path +- `GroupProfile` — group name and optional description; one logical profile per cloned cell - `GroupMembership` — agent membership record; links removed on leave, entry retained as audit trail - `WorkLog` — planning-level contribution record (no PPRs; ADR-GROUP-04) - `SoftLink` — planning-level link to an NDO (no PPRs; ADR-GROUP-04) -### Coordinator API (15 externs) +### Coordinator API (16 externs) + +`init`, `create_group`, `get_group`, `update_group`, `get_my_group`, `join_group`, `leave_group`, `get_group_members`, `is_member`, `log_work`, `delete_work_log`, `get_work_logs`, `get_my_work_logs`, `create_soft_link`, `delete_soft_link`, `get_soft_links` -`create_group`, `get_group`, `get_all_groups`, `get_my_group`, `update_group`, `join_group`, `leave_group`, `get_group_members`, `is_member`, `log_work`, `get_work_logs`, `get_my_work_logs`, `create_soft_link`, `get_soft_links`, `init` +There is no `get_all_groups` extern in a Group cell; each cell represents one isolated Group. Cross-Group discovery belongs to the Lobby DNA. ### Sweettest Coverage @@ -172,7 +255,27 @@ Group cells use the **cloned-cell pattern**: a single Group DNA template is inst ### UI Service Layer -`ui/src/lib/services/zomes/group.service.ts` — stub replaced with real `callZome` implementation targeting cloned cells; `GroupServiceTag` interface unchanged (ADR-GROUP-03). +`ui/src/lib/services/zomes/group.service.ts` targets cloned cells and exposes the subset currently needed by the UI: Group lookup, members, WorkLog queries, and SoftLink queries/creation. The backend's update/delete and work-entry functions are not all surfaced through this service yet. + +`WorkLogFeed.svelte` and `SoftLinkList.svelte` exist as early components, but are not currently integrated into `GroupView`; the visible Group page focuses on members and Group-associated NDOs. + +--- + +## NDO Federation Extensions ✅ Implemented (PR #103) + +The governance zome includes three additional public entry families: + +- **`NdoHardLink`** — typed cross-NDO/cross-DNA links (`Component`, `DerivedFrom`, `Supersedes`) backed by an EconomicEvent fulfillment hash +- **`Contribution`** — peer-validated `Work`/`Modify` contributions with optional effort and cross-DNA WorkLog references +- **`Agreement`** — versioned benefit-redistribution clauses with Primary Accountable Agent authorization + +Implemented coordinator APIs: + +- Hard links: `create_ndo_hard_link`, `get_ndo_hard_links`, `get_ndo_hard_link`, `get_ndo_hard_links_by_type` +- Contributions: `validate_contribution`, `get_ndo_contributions`, `get_agent_contributions`, `get_contribution` +- Agreements: `create_agreement`, `update_agreement`, `get_current_agreement`, `get_agreement` + +These are Nondominium-native federation primitives. They are not yet a full version DAG, automatic upstream benefit propagation, or Unyt Smart Agreement/RAVE integration. Sweettest coverage is partial: the hard-link scenario is active; Agreement and Contribution scenarios currently use `#[ignore]`. --- @@ -205,14 +308,15 @@ Resource lifecycle, governance/PPR wiring, and production hardening via hREA are ### MVP UI — Lobby → Group → NDO ✅ Implemented -Full three-level hierarchical UI as specified in `documentation/requirements/ui_design.md` (MVP section) and `documentation/specifications/ui_architecture.md`. The UI was substantially restructured in the UI-restructure sprint to make the Lobby the persistent outer shell with a permanent sidebar, and to fix NDO data display. +Full three-level hierarchical UI as specified in `documentation/requirements/ui_design.md` (MVP section) and `documentation/specifications/ui_architecture.md`. Lobby and Group presentation layers are wired. Automatic `Person` creation on the agent's first DHT-active action is **not** currently enforced by the UI. The UI was substantially restructured in the UI-restructure sprint to make the Lobby the persistent outer shell with a permanent sidebar, and to fix NDO data display. #### Shared Types - `NdoDescriptor`, `NdoInput`, `UpdateLifecycleStageInput`, `NdoTransitionHistoryEvent` — `packages/shared-types/src/resource.types.ts` -- `PropertyRegime` — 4 variants: Private, Commons, Nondominium, CommonPool (Collective and Pool removed) +- Rust's canonical `PropertyRegime` has 6 variants: `Private`, `Commons`, `Collective`, `Pool`, `CommonPool`, `Nondominium` +- **Current frontend mismatch**: `packages/shared-types/src/resource.types.ts` still exposes only 4 variants (`Private`, `Commons`, `Nondominium`, `CommonPool`); `Collective` and `Pool` still need to be propagated through frontend types, schemas, form options, filters, and color/label maps - `LobbyUserProfile`, `GroupMemberProfile` — three-level identity model -- Extended `GroupDescriptor` with `ndoHashes`, `memberProfile`, `createdBy`, `createdAt` +- Extended `GroupDescriptor` with clone-cell identifiers, derived/deprecated `ndoHashes`, local `memberProfile`, and optional presentation metadata #### Service Layer @@ -237,23 +341,24 @@ Full three-level hierarchical UI as specified in `documentation/requirements/ui_ - `LobbyView.svelte` — page header + `NdoBrowser`; **`$effect` mirrors `lobbyStore.myPerson` into `appContext` and triggers `loadNdos()` — it does not set `appContext.currentView`** so the lobby shell does not override `'ndo'` when an NDO page is mounted - `UserProfileForm.svelte` — Lobby profile create/edit (modal + page modes; nickname required) -- `NdoBrowser.svelte` — multi-select filter chips: LifecycleStage × ResourceNature × PropertyRegime (4 variants); "No NDOs yet" empty state +- `NdoBrowser.svelte` — multi-select filter chips: LifecycleStage × ResourceNature × PropertyRegime; currently offers the frontend's 4 regimes, pending propagation of `Collective` and `Pool`; "No NDOs yet" empty state - `NdoCard.svelte` — NDO summary card with lifecycle/nature/regime badges; populates `ndo-cache` before navigating #### Components — Group Level - `GroupView.svelte` — group header, "Create NDO" button, group-scoped `NdoBrowser`; **fixed**: uses `$effect` instead of `onMount` so group data reloads correctly when navigating between groups -- `NdoCreateModal.svelte` — 5-field form (name, 4-variant regime, nature, stage, description), uniqueness check, Effect-TS errors, navigates to NDO page on success +- `NdoCreateModal.svelte` — 5-field form (name, regime, nature, stage, description), uniqueness check, Effect-TS errors, navigates to NDO page on success; currently exposes 4 of the backend's 6 regimes - `GroupProfileModal.svelte` — per-group profile disclosure preferences (first visit only) #### Components — NDO Level -- `NdoView.svelte` — detail card with labeled Description / Property Regime / Resource Nature / Lifecycle Stage / Created; loading skeleton + retry-able DHT refresh error banner; Join NDO (inline **Coming soon**); **Associate with a group** opens `AssociateNdoModal` (multi-select eligible groups → `associateNdoWithGroup`); Fork opens `ForkNdoModal` when Holochain is connected (`appContext.myAgentPubKey`). Descriptor seeded from `ndo-cache` then refreshed via `NdoService.getNdoDescriptorForSpecActionHash`. **Reactive fix**: first `$effect` decodes URL hash into a local `hash` variable before assigning `appContext.selectedNdoId`; reading `$state(specActionHash)` in the same effect after writing it caused Svelte **effect_update_depth_exceeded** and left header buttons non-functional. +- `NdoView.svelte` — detail card with labeled Description / Property Regime / Resource Nature / Lifecycle Stage / Created; loading skeleton + retry-able DHT refresh error banner; Join NDO (inline **Coming soon**); **Associate with a group** opens `AssociateNdoModal`; Fork opens `ForkNdoModal` when Holochain is connected. Descriptor is seeded from `ndo-cache` then refreshed from the DHT. - `AssociateNdoModal.svelte` — lists groups excluding those whose `ndoHashes` already contain this spec; loads groups via `lobbyStore.loadGroups()` on mount -- `NdoIdentityLayer.svelte` — initiator profile link, lifecycle transition button (initiator-only), `TransitionHistoryPanel`; 4-variant `PropertyRegime` color map +- `NdoIdentityLayer.svelte` — initiator profile link, lifecycle transition button (initiator-only), `TransitionHistoryPanel`; its color map still covers only the 4 frontend regimes - `LifecycleTransitionModal.svelte` — full state machine (mirrors Rust), Deprecated + Hibernating special cases - `TransitionHistoryPanel.svelte` — collapsible history: from/to stage, agent, timestamp, event_hash + copy-to-clipboard - `ForkNdoModal.svelte` — informational fork friction modal with copy-initiator-pubkey CTA +- NDO tabs: Resources, Governance, and Activity render current service-backed data; Composition is still a placeholder #### Routing @@ -272,6 +377,7 @@ The dev runtime is the **browser** (Electron/`hc-spin` superseded). `scripts/lau ### Not Yet Implemented (UI) +- Complete six-variant PropertyRegime support: `Collective` and `Pool` are present in Rust but missing from frontend shared types, schemas, forms, filter options, and display maps - "Join NDO" backend implementation (button is a placeholder; UI flow + API contract only) - Person management components (issue #8) - Resource management components (issue #9) @@ -280,7 +386,7 @@ The dev runtime is the **browser** (Electron/`hc-spin` superseded). `scripts/lau - Economic Process workflow UI (issues #28–#32) - Role management / agent progression UI (issues #33–#34) -> Group DNA backend ✅ Complete (PR #107) — cloned-cell architecture, 4 entry types, 15 coordinator externs, 13 Sweettest cases. Multi-member group invites, DHT member lists, reactive join, idempotent membership self-heal (`ensureMembership`), and pull-based reactivity (tab focus + gentle poll) for shared-group items are wired in the UI (see Group Level components above). Push reactivity via Holochain `remote_signal` is the documented next step (`TODO(signals)` markers in `zome_group/src/lib.rs`, `GroupView.svelte`, `lobby.service.ts`). +> Group DNA backend ✅ Complete for its current scope (PR #107) — cloned-cell architecture, 4 entry types, 16 coordinator externs, 13 Sweettest cases. Multi-member Group invites, DHT member lists, reactive join, idempotent membership self-heal (`ensureMembership`), and pull-based reactivity (tab focus + gentle poll) for shared-group items are wired in the UI. Push reactivity via Holochain `remote_signal` is the documented next step. --- @@ -288,7 +394,7 @@ The dev runtime is the **browser** (Electron/`hc-spin` superseded). `scripts/lau ### Sweettest (Rust) — Primary ✅ -All new tests are written in Sweettest in `dnas/nondominium/tests/src/`. +All new backend integration tests use Sweettest. Core-DNA tests live in `dnas/nondominium/tests/src/`; Lobby and Group have separate Sweettest packages. **Shared setup utilities** (`common::conductors`): @@ -296,10 +402,20 @@ All new tests are written in Sweettest in `dnas/nondominium/tests/src/`. - `setup_three_agents()` — three conductors, nondominium DNA - `setup_dual_dna_two_agents()` — two conductors, nondominium + hREA DNAs -**Test modules:** +**Registered core test modules** (`dnas/nondominium/tests/Cargo.toml`): + +- `misc` — zome connectivity +- `person` — Person zome + hREA bridge +- `resource` — ResourceSpecification, EconomicResource, GovernanceRule, transition, and NDO Layer 0 behavior +- `governance` — federation hard links are active; Agreement and Contribution scenarios are currently ignored +- `nondominium` — NDO lifecycle/integrity scenarios + +**Separate DNA suites:** + +- `dnas/lobby/tests` — 5 Lobby scenarios +- `dnas/group/tests` — 13 Group scenarios -- `misc/mod.rs` — zome connectivity (ping) -- `person/mod.rs` — person zome + hREA bridge tests +Active Sweettest coverage is useful but incomplete. Across core + Lobby + Group suites there are about 33 active tests, with ignored governance Agreement/Contribution cases. The PPR coordinator prototype, Person capability/device paths, and several partially stubbed governance flows still lack complete active coverage. ### Tryorama (TypeScript) — Deprecated ⚠ @@ -328,25 +444,39 @@ CARGO_TARGET_DIR=target/native-tests cargo test --package nondominium_sweettest | Area | Status | | ------------------------------------------------------ | -------------- | -| Person management (profiles, roles, capability grants) | ✅ Complete | -| Resource specifications and economic resources | ✅ Complete | -| ValueFlows action vocabulary + economic events | ✅ Complete | -| Commitments and claims | ✅ Complete | -| PPR data structures + cryptographic auth | ✅ Complete | -| hREA Phase 1 (Person/ReaAgent bridge) | ✅ Complete | -| SvelteKit + UnoCSS + Melt UI next-gen setup | ✅ Complete | +| Multi-DNA hApp packaging (Lobby/NDO/hREA/Group) | ✅ Complete for current bundle | +| Person profiles and Agent↔Person mapping | ✅ Implemented | +| Person roles, capabilities, and device support | 🔄 Implemented APIs; capability sharing is still prototype-quality | +| Role promotion and specialized validation | 🔄 Partial; placeholder/auto-approval paths remain | +| Resource specifications and economic resources | ✅ CRUD/query model implemented | +| GovernanceRule persistence | ✅ Implemented | +| GovernanceRule semantic enforcement | ❌ Not implemented | +| ValueFlows action vocabulary + EconomicEvents | ✅ Implemented | +| Commitments and Claims | ✅ Implemented | +| PPR types, validation, local queries, and summaries | 🔄 Prototype | +| Fully authenticated automatic bilateral PPR workflow | ❌ Not implemented | +| Governance validation APIs | 🔄 Partial | +| Governance-as-Operator Request→Evaluate→Apply path | ❌ Not implemented | +| NondominiumIdentity Layer 0 | ✅ Implemented | +| PropertyRegime backend enum (6 variants) | ✅ Implemented | +| PropertyRegime frontend support (all 6 variants) | 🔄 4 of 6 currently exposed | +| NDO federation hard links/contributions/agreements | 🔄 Implemented; Agreement/Contribution tests ignored | +| Lobby DNA backend | ✅ Implemented | +| Group DNA backend (cloned-cell architecture) | ✅ Complete for current scope | +| hREA Phase 1 (Person/ReaAgent bridge) | ✅ Implemented | +| hREA Phases 2–4 | ❌ Not started | +| SvelteKit + UnoCSS + Melt UI next-gen setup | ✅ Implemented | | Effect-TS service layer | ✅ Complete (PR #97) | -| NondominiumIdentity (Layer 0 identity anchor) | ✅ Complete | | MVP UI — Persistent Lobby sidebar (all routes) | ✅ Complete | | MVP UI — Lobby → Group → NDO hierarchy | ✅ Complete | -| MVP UI — Three-level identity (Lobby/Group/Agent) | ✅ Complete | +| MVP UI — Three-level identity (Lobby/Group/Agent) | 🔄 Lobby + Group presentation wired; first-action Person creation not enforced | | MVP UI — NDO creation within Group context | ✅ Complete | -| MVP UI — NDO detail page (detail card + header actions) | ✅ Complete (Join placeholder, Associate modal, Fork modal — smoke-tested) | -| MVP UI — NDO filter browser (3-dimension chips) | ✅ Complete | +| MVP UI — NDO detail page | 🔄 Implemented; Join and Composition are placeholders | +| MVP UI — NDO filter browser (3-dimension chips) | 🔄 Complete for current 4 frontend regimes | | MVP UI — Lifecycle transition + history panel | ✅ Complete | | MVP UI — Fork friction modal | ✅ Complete | | MVP UI — Associate NDO with group modal | ✅ Complete | -| MVP UI — Join NDO (placeholder) | ✅ Complete (placeholder) | +| MVP UI — Join NDO | ❌ Backend not implemented | | MVP UI — First-time user profile modal (root layout) | ✅ Complete | | MVP UI — Multi-member group invites + DHT member list | ✅ Complete | | MVP UI — Reactive group join (gossip-retry + fallback) | ✅ Complete | @@ -354,17 +484,11 @@ CARGO_TARGET_DIR=target/native-tests cargo test --package nondominium_sweettest | MVP UI — Pull reactivity for shared-group items (focus + poll) | ✅ Complete | | Push reactivity via Holochain signals | ❌ Not started (`TODO(signals)`) | | Dev harness — per-agent web instances (ports, auto-open) | ✅ Complete | -| PropertyRegime reduced to 4 canonical variants | ✅ Complete | -| Sweettest scaffold + person tests | ✅ Complete | +| Active Sweettest suites (core + Lobby + Group) | ✅ Implemented | | Economic processes (Use/Transport/Storage/Repair) | ❌ Not started | -| PPR receipt generation and EOL workflows | ❌ Not started | -| Governance-as-Operator architecture | ❌ Not started | -| Agent promotion + role validation workflows | 🔄 Partial | | Person management UI components | ❌ Not started | | Economic Process UI | ❌ Not started | | PPR reputation visualization | ❌ Not started | -| Group DNA backend (cloned-cell architecture) | ✅ Complete (PR #107) | -| hREA Phase 2–4 | ❌ Not started | --- @@ -374,13 +498,13 @@ The following are documented and traceable to REQ-NDO-\* in `documentation/requi | Track | Design sources | Implementation status | | ------------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -| **NDO Layer 0 (identity anchor)** | `ndo_prima_materia.md` §§4, 8; REQ-NDO-L0-01–07 | **Complete** (#80) — `NondominiumIdentity` entry with lifecycle validation; REQ-NDO-L0-05 (EconomicEvent ref) and -07 (facet anchors) not yet enforced | +| **NDO Layer 0 (identity anchor)** | `ndo_prima_materia.md` §§4, 8; REQ-NDO-L0-01–07 | **Implemented** (#80/#84) — identity, lifecycle validation, and facet anchors exist; required EconomicEvent generation and complete link-integrity hardening remain pending | | **NDO Layers 1 & 2** | `ndo_prima_materia.md` §§4, 8, 10; `resources.md` §3 | Not started — Layer 1 (Specification links), Layer 2 (Process links), cross-layer link types pending | -| **Lifecycle vs operational state split** | `ndo_prima_materia.md` §5, §9.4 (`REQ-NDO-OS-01`–`06`) | Not started — `ResourceState` still conflated (see `zome_resource` TODOs) | +| **Lifecycle vs operational state split** | `ndo_prima_materia.md` §5, §9.4 (`REQ-NDO-OS-01`, `REQ-NDO-OS-06`) | ✅ Data layer — `OperationalState` on `EconomicResource`; governance-operator transitions (`REQ-NDO-OS-02`–`05`) deferred | | **Unyt (EconomicAgreement, RAVE)** | `ndo_prima_materia.md` §6.6, §11.5; `unyt-integration.md`; REQ-NDO-CS-07–CS-11 | Not started — no Unyt cell / RAVE validation in governance zome | | **Flowsta (agent linking, IdentityVerification)** | `ndo_prima_materia.md` §6.7, §11.6; `flowsta-integration.md`; REQ-NDO-CS-12–CS-15 | Not started — `flowsta-agent-linking` zomes not bundled | | **Person capability slot (G15)** | `agent.md` §3.2; `person_zome.md`; REQ-AGENT-11, REQ-NDO-AGENT-07 | Not started — no `FlowstaIdentity` links on `Person` hash | -| **Lobby DNA (multi-network federation entry point)** | `post-mvp/lobby-dna.md` REQ-LOBBY-*; `specifications/post-mvp/lobby-architecture.md` | **Complete** (#103) — `zome_lobby` DNA with `LobbyAgentProfile` + `NdoAnnouncement` entry types, Sweettest suite (`lobby_sweettest`), `lobby` role in `happ.yaml`, Moss manifest. Group DNA complete (#107). | -| **NDO DNA extensions (NdoHardLink, Contribution, Agreement)** | `post-mvp/lobby-dna.md` REQ-NDO-EXT-01–16; `specifications/post-mvp/lobby-architecture.md §6` | **Complete** (#103) — three new entry types and link types added to `zome_gouvernance` integrity; coordinator modules `hard_link.rs`, `contribution.rs`, `agreement.rs` with Sweettest coverage. | +| **Lobby DNA (multi-network federation entry point)** | `post-mvp/lobby-dna.md` REQ-LOBBY-*; `specifications/post-mvp/lobby-architecture.md` | **Implemented** (#103) — Lobby DNA with `LobbyAgentProfile` + `GroupAnnouncement`, 9 coordinator externs, 5 Sweettest scenarios, `lobby` role in `happ.yaml`, and Moss manifest. Group DNA complete for its current scope (#107). | +| **NDO DNA extensions (NdoHardLink, Contribution, Agreement)** | `post-mvp/lobby-dna.md` REQ-NDO-EXT-01–16; `specifications/post-mvp/lobby-architecture.md §6` | **Implemented** (#103) — entry types, link types, and coordinator modules exist; hard-link Sweettest is active, while Agreement/Contribution scenarios are currently ignored. | See `documentation/implementation_plan.md` Section 12 for a phased checklist aligned with the prima materia. diff --git a/documentation/hREA/integration-strategy.md b/documentation/hREA/integration-strategy.md index 0ade73c..6595c8e 100644 --- a/documentation/hREA/integration-strategy.md +++ b/documentation/hREA/integration-strategy.md @@ -74,7 +74,7 @@ hREA exposes a GraphQL API intended for UI consumption. For Nondominium, integra | unit | `String` | `unit_of_effort: Option` (Unit is a first-class entry) | | custodian | `AgentPubKey` (direct) | `primary_accountable: Option` (links to ReaAgent entry) | | location | `Option` | `current_location: Option` (same) | -| state | `ResourceState` enum | `state: Option` (string-based) | +| operational_state | `OperationalState` enum on `EconomicResource` | `state: Option` (string-based) | | spec link | via `SpecificationToResource` link | `conforms_to: Option` (embedded) | | — | missing | `contained_in: Option` (nested resources) | | — | missing | `stage: Option` (lifecycle stage entry) | diff --git a/documentation/implementation_plan.md b/documentation/implementation_plan.md index e473be6..785451b 100644 --- a/documentation/implementation_plan.md +++ b/documentation/implementation_plan.md @@ -4,19 +4,19 @@ This plan details the phased implementation of the nondominium hApp, a decentralized, organization-agnostic resource management system built on Holochain and ValueFlows. The implementation builds incrementally on the existing working foundation to deliver Economic Processes, Private Participation Receipt (PPR) reputation, agent capability progression, and cross-zome coordination, while aligning with the **generic Nondominium Object (NDO)** model where that work is scheduled. -**MVP vs post-MVP (normative boundary):** Per [requirements.md §2.3](requirements/requirements.md), the **current MVP** in this repository is the combination of `ResourceSpecification`, `EconomicResource`, and `GovernanceRule` with governance-as-operator patterns. **NDO-wide** requirements (three-layer model, lifecycle versus operational state, capability slots, migration, REQ-NDO-*) live in [ndo_prima_materia.md](requirements/ndo_prima_materia.md) and are **not** implied by the MVP DNA until explicitly implemented. Phases 2–4 below are mostly **MVP core** delivery; the **NDO model and migration** track extends or refactors that foundation when scheduled. Post-MVP agent ontology (REQ-AGENT-*, REQ-NDO-AGENT-*) is specified in [requirements.md §4.4](requirements/requirements.md), with background analysis in [archives/agent.md](archives/agent.md). +**MVP vs post-MVP (normative boundary):** Per [requirements.md §2.3](requirements/requirements.md), the MVP resource substrate is `ResourceSpecification`, `EconomicResource`, and `GovernanceRule`. The repository has also implemented NDO Layer 0 (`NondominiumIdentity`), Lobby and Group DNAs, PPR prototypes, and NDO federation extensions. **Governance-as-Operator** remains specified rather than coded as a Request→Evaluate→Apply path. **NDO-wide** requirements beyond the implemented subset (Layers 1/2 activation, operational-state split, capability slots, migration, REQ-NDO-*) remain governed by [ndo_prima_materia.md](requirements/ndo_prima_materia.md). Phases 2–4 below distinguish implemented foundations from remaining production workflows. Post-MVP agent ontology (REQ-AGENT-*, REQ-NDO-AGENT-*) is specified in [requirements.md §4.4](requirements/requirements.md). **Source-NDO** is an **optional application profile** (REQ-SOURCE-APP-*, [requirements.md §4.6](requirements/requirements.md)) — not required for Project NDOs or resource-mutualisation apps; see §12.7. ### 1.1 Requirements map (normative sources) -This index is the entry point for phased delivery. **Current focus:** Layer 1 UI on the NDO detail view (`/ndo/:hash`) — **ResourceSpecification** (the shareable form), **GovernanceRule** (embedded rules governing agent–resource interaction), and **Process** readiness (what agents may do under those rules; Layer 2 / REQ-PROC-*). Layer 0 identity UI is implemented; Layer 1 activation (`NDOToSpecification`) and Layer 2 activation (`NDOToProcess`) are normative but not yet wired in DNA — UI work proceeds against existing MVP zome APIs plus prima materia REQ-NDO-L1-* / REQ-NDO-L2-* targets. Status cross-check: [IMPLEMENTATION_STATUS.md](IMPLEMENTATION_STATUS.md). +This index is the entry point for phased delivery. **Current implementation baseline:** Layer 0 identity and lifecycle UI are implemented; Resources, Governance, and Activity tabs render existing service-backed data, while Composition remains a placeholder. Layer 1 activation (`NDOToSpecification`) and Layer 2 activation (`NDOToProcess`) are normative but not yet wired in DNA. The next work should connect those layers and complete Economic Process, governance-rule evaluation, and authenticated PPR workflows rather than recreate already-shipped entry types and APIs. Status cross-check: [IMPLEMENTATION_STATUS.md](IMPLEMENTATION_STATUS.md). #### Core normative (PRD, NDO model, UI, data model) | Source | Role | |--------|------| -| [requirements.md](requirements/requirements.md) | PRD — REQ-USER-*, REQ-RES-*, REQ-GOV-*, REQ-PROC-*, REQ-AGENT-* (§4.4 post-MVP agent ontology); REQ-UI-* (§4.5 MVP UI) | +| [requirements.md](requirements/requirements.md) | PRD — REQ-USER-*, REQ-RES-*, REQ-GOV-*, REQ-PROC-*, REQ-AGENT-* (§4.4 post-MVP agent ontology); REQ-UI-* (§4.5 MVP UI); REQ-SOURCE-APP-* / REQ-SOURCE-* (§4.6 optional Source profile) | | [ndo_prima_materia.md](requirements/ndo_prima_materia.md) | NDO layers (L0/L1/L2), lifecycle vs operational state, capability surface; **REQ-NDO-L1-*** (§9.2), **REQ-NDO-L2-*** (§9.3), REQ-NDO-* (§9), migration (§10) | -| [ui_design.md](requirements/ui_design.md) | UI vision — MVP Layer 0 complete; NDO view tabs (Resources, Governance, Composition, Activity) stubbed for Layer 1+ content | +| [ui_design.md](requirements/ui_design.md) | UI vision — MVP Layer 0 complete; Resources, Governance, and Activity tabs service-backed; Composition and Join NDO remain incomplete | | [specifications/ui_architecture.md](specifications/ui_architecture.md) | Implemented UI stack, routes, stores, services (`resource.service.ts`, `governance.service.ts`), component map | | [specifications/specifications.md](specifications/specifications.md) | Technical data structures — `ResourceSpecification`, `GovernanceRule`, `EconomicResource`, `EconomicProcess`, VfAction, cross-zome governance interface | @@ -27,7 +27,8 @@ This index is the entry point for phased delivery. **Current focus:** Layer 1 UI | [zomes/resource_zome.md](zomes/resource_zome.md) | **Implemented** coordinator/integrity API — `ResourceSpecification`, `GovernanceRule`, `EconomicResource`; planned `NDOToSpecification` / `DigitalAsset` links | | [requirements/resources.md](requirements/resources.md) | Resource ontology — implemented vs planned; Layer 1 activation gap; governance defaults from `PropertyRegime` × `ResourceNature` (non-normative REQ IDs) | | [post-mvp/project-type-ndo-specifications.md](requirements/post-mvp/project-type-ndo-specifications.md) | Structured know-how bundles for project-type NDOs (OSHWA / Open Know-How → Layer 1 assets); lifecycle-matched completeness | -| [post-mvp/source-ndo-requirements.md](requirements/post-mvp/source-ndo-requirements.md) | **Source-NDO** — `Source` as third ontological primitive; `SourceProfile` Layer 0 extension; adaptive cybernetic governance loop; `vf:Source` ValueFlows extension (REQ-SOURCE-*) | +| [post-mvp/source-ndo-requirements.md](requirements/post-mvp/source-ndo-requirements.md) | **Source-NDO (optional profile)** — `Source` as third flow endpoint when an application governs generative systems; `SourceProfile`, adaptive loop, `vf:Source` (REQ-SOURCE-*); applicability REQ-SOURCE-APP-* in [requirements.md §4.6](requirements/requirements.md) | +| [post-mvp/Source-NDO.md](requirements/post-mvp/Source-NDO.md) | Paper planning scaffold — thesis, Ostrom/VF argument structure (informative) | | [post-mvp/source-ndo-paper.md](requirements/post-mvp/source-ndo-paper.md) | Academic grounding: Occam's razor proof, river case study, Ostrom SES mapping (informative) | | [post-mvp/versioning.md](requirements/post-mvp/versioning.md) | Version DAG — **REQ-NDO-L1-03** (multiple `ResourceSpecification` links per NDO identity) | | [post-mvp/digital-resource-integrity.md](requirements/post-mvp/digital-resource-integrity.md) | Content-addressed manifests, composable verification — **REQ-NDO-L1-06** `DigitalAsset` capability slots (prima materia §9.2) | @@ -62,6 +63,13 @@ This index is the entry point for phased delivery. **Current focus:** Layer 1 UI | [post-mvp/lobby-dna.md](requirements/post-mvp/lobby-dna.md) | Multi-network federation — Lobby / Group / NDO DNA extensions (REQ-LOBBY-*, REQ-GROUP-*, REQ-NDO-EXT-*) | | [requirements/agent.md](requirements/agent.md) | Agent ontology — roles, affiliation, `AgentContext` (post-MVP); background for governance participation and process access | +### 1.2 Status synchronization convention + +- [IMPLEMENTATION_STATUS.md](IMPLEMENTATION_STATUS.md) is the evidence-based inventory of current code. +- In this plan, `[x]` means the stated scope exists now; `[ ]` means remaining work. A checked foundation does not imply that its unchecked production workflow is complete. +- When a feature ships, update both documents in the same change: record evidence and limitations in the status document, then close or split the corresponding plan task. +- Do not mark a whole phase complete while it still contains implementation tasks; use “foundation delivered” or “partial” for mixed phases. + --- ## 2. Implementation Principles @@ -79,7 +87,7 @@ Judge outcomes by **systemic viability** — anti-fragility, evolvability, coord | **Governance-as-operator** | Decouple the **data substrate** (`zome_resource`) from **regulatory signaling** (`zome_gouvernance`). Business and governance logic must not be hard-coded into core entry schemas; rules evolve as mutable data without destructive migrations (REQ-ARCH-07, REQ-ARCH-08). | | **Stigmergic coordination** | Prefer discoverable traces, anchor links, reputation signals (PPRs), and **CapabilitySlot** attachments over central orchestrators. Agents coordinate by modifying a shared environment — the DHT — not by a mediating platform service. | | **Fractal composability** | Use the same coordination primitives at agent, group, NDO, and federation scales. **Trust and integrity compose** through hierarchies (atomic → component → composite): local verification at each level yields global coherence; changes re-verify only affected paths (digital integrity, holonic NDO links — post-MVP). | -| **Path-dependency awareness** | Before refactors or major UI/API contracts, scan legacy choices (MVP orphan `ResourceSpecification` entries, localStorage group shells, stub tabs). Do not inherit constraints blindly — document migration windows (REQ-NDO-MIG-*) when Layer 1 UI bridges old and new models. | +| **Path-dependency awareness** | Before refactors or major UI/API contracts, scan legacy choices (orphan `ResourceSpecification` entries, pre-NDO economic-resource flows, four-regime frontend types, and remaining placeholder surfaces). The localStorage Group shell has already migrated to cloned Group cells; only per-Group presentation preferences remain local. Document migration windows (REQ-NDO-MIG-*) when Layer 1 bridges old and new models. | | **Anti-fragility** | Disruption should teach, not only hurt. Disputes, validation failures, and adversarial behaviour must generate auditable signals (PPRs, validation receipts, governance events) that improve future coordination — not merely error screens. | ### 2.2 Nondominium enactments @@ -106,7 +114,7 @@ Judge outcomes by **systemic viability** — anti-fragility, evolvability, coord The **three-layer model** ([ndo_prima_materia.md §4](requirements/ndo_prima_materia.md)) structures resources as: -- **Layer 0 — Identity**: `NondominiumIdentity` (stable anchor, tombstone at end of life); only `lifecycle_stage` evolves after creation (REQ-NDO-L0-*). +- **Layer 0 — Identity**: `NondominiumIdentity` (stable anchor, tombstone at end of life); identity fields are immutable while lifecycle updates may change `lifecycle_stage`, `hibernation_origin`, and the one-time `successor_ndo_hash` (REQ-NDO-L0-*). - **Layer 1 — Specification**: Activated by `NDOToSpecification` → `ResourceSpecification` (governance rules, discoverable form); may be dormant/archived while L0 remains (REQ-NDO-L1-*). - **Layer 2 — Process**: Activated by `NDOToProcess` → ValueFlows `Process`; hosts commitments, claims, events, PPRs (REQ-NDO-L2-*). @@ -135,78 +143,93 @@ Work below is grouped into **parallel tracks** so MVP delivery, NDO migration, a | **NDO model and migration** | `NondominiumIdentity`, `NDOToSpecification` / `NDOToProcess`, holonic links, `CapabilitySlot`, lifecycle plus operational split, faceted discovery links, one-time migration (REQ-NDO-MIG-*) | [ndo_prima_materia.md](requirements/ndo_prima_materia.md) §§8–10, §9 | | **Agent ontology** | REQ-AGENT-* / REQ-NDO-AGENT-* items under Phases 2–4 | [requirements.md §4.4](requirements/requirements.md); [archives/agent.md](archives/agent.md) for OVN background | | **Unyt / Flowsta** | Phased integration; governance enforcement in later phases | Section 12.2–12.3; REQ-NDO-CS-07–CS-15 | -| **Extended post-MVP** | Many-to-many flows, versioning, digital integrity, RTP-FP, VF DSL, **Lobby DNA federation layer** — reference and ordering only in Section 12.5–12.6 | `documentation/requirements/post-mvp/*.md` | +| **Source-NDO application profile** | Optional third VF primitive (`vf:Source`) for applications governing generative ecological/knowledge systems — **not** activated for ordinary Project NDOs or mature-resource mutualisation (e.g. shared 3D printer). Opt-in modules only; default UI stays Agent + Resource. | [requirements.md §4.6](requirements/requirements.md) REQ-SOURCE-APP-*; [source-ndo-requirements.md](requirements/post-mvp/source-ndo-requirements.md); §12.7 | +| **Extended post-MVP** | Many-to-many flows, full version DAG, digital integrity, RTP-FP, VF DSL, Moss contract, and remaining federation work. Lobby/Group DNAs and the first NDO federation primitives are already implemented. | `documentation/requirements/post-mvp/*.md` | -**Phase 2.2 and the NDO track:** Checklists for `LifecycleStage` / `OperationalState`, split discovery links, and process-aware resource work **implement REQ-NDO-LC-*, REQ-NDO-OS-*, and parts of REQ-NDO-L2-*** once `NondominiumIdentity` and NDO links exist; until then, some items remain preparatory. Full L0-first creation and migration follow Section 12.1 and REQ-NDO-MIG-*. +**Phase 2.2 and the NDO track:** `NondominiumIdentity`, `LifecycleStage`, lifecycle validation, and lifecycle facet links already exist. Remaining work implements `OperationalState`, `NDOToSpecification` / `NDOToProcess`, process-aware resource transitions, and the rest of REQ-NDO-LC-*, REQ-NDO-OS-*, and REQ-NDO-L2-*. Legacy-resource migration remains in Section 12.1 and REQ-NDO-MIG-*. + +**Source-NDO track (optional application profile):** Follows **dynamic complexity matching** — Agent + Resource remain the universal baseline. Source modules activate only when an application's domain requires governing a generative system (watershed, river, fishery, knowledge commons) and its boundary effects. **Not in scope** for Project-type NDOs (e.g. open-hardware design) or resource-mutualisation NDOs (e.g. sharing a 3D printer within or between Groups). When enabled, the track adds `SourceProfile`, coupling links, the `Steward` role, `vf:Source` boundary events, and an adaptive governance loop. Full adaptive enforcement depends on Governance-as-Operator (§12.7); Phases A–B can proceed on opt-in data model and event recording without changing the default NDO creation UI. --- ## 5. Implementation Phases -### Phase 1: Foundation Layer ✅ **COMPLETED** (Existing Working Code) +### Phase 1: Foundation Layer ✅ **DELIVERED** (Existing Working Code) -#### 3.1 Agent Identity & Role System (`zome_person`) ✅ **COMPLETED** +#### 1.1 Agent Identity & Role System (`zome_person`) ✅ **CORE IMPLEMENTED** -- [x] Implement `Person` (public info) and `PrivateData` (private entry, PII). +- [x] Implement `Person` (public info) and `PrivatePersonData` (private entry, PII). - [x] Implement `PersonRole` entry with validation metadata and links to validation receipts. - [x] **Modular Architecture**: Refactored into `person.rs`, `private_data.rs`, `role.rs` modules - [x] **Comprehensive Error Handling**: PersonError enum with detailed error types - [x] **Core Functions**: Profile management, role assignment, private data storage -- [x] **Testing**: Comprehensive test suite with foundation, integration, and scenario tests +- [x] **Multi-device identity**: `Device` and `AgentPersonRelationship` entries, links, and coordinator APIs +- [x] **Foundation testing**: Active Person/hREA Sweettests +- [ ] **Remaining testing**: Complete capability, role, device, and promotion Sweettest coverage -#### 3.2 Resource Management (`zome_resource`) ✅ **COMPLETED** +#### 1.2 Resource Management (`zome_resource`) ✅ **CORE IMPLEMENTED** -- [x] Implement `ResourceSpecification` with embedded governance rules. +- [x] Implement `ResourceSpecification` with separately stored and linked `GovernanceRule` entries. - [x] Implement `EconomicResource` with custodian tracking and state management. - [x] **Modular Architecture**: Refactored into `resource_specification.rs`, `economic_resource.rs`, `governance_rule.rs` - [x] **Comprehensive Error Handling**: ResourceError enum with governance violation support - [x] **Signal System**: Complete post-commit signal handling for DHT coordination - [x] **Core Functions**: Resource specification and economic resource CRUD operations -- [x] **Testing**: Comprehensive test suite with integration and scenario coverage +- [x] **NDO Layer 0**: `NondominiumIdentity`, 10-stage lifecycle validation, hibernation/successor metadata, and discovery facets +- [x] **Foundation testing**: Active Resource/NDO Sweettests +- [ ] **Remaining testing**: Close uncovered Resource/NDO integrity and workflow paths -#### 3.3 Governance Foundation (`zome_gouvernance`) ✅ **CORE COMPLETE** +#### 1.3 Governance Foundation (`zome_gouvernance`) 🔄 **FOUNDATION IMPLEMENTED** - [x] **Basic VfAction Enum**: Type-safe economic action vocabulary - [x] **Validation Infrastructure**: ValidationReceipt creation and management - [x] **Economic Event Logging**: Basic economic event recording - [x] **Cross-Zome Functions**: Core validation functions for resource and agent validation - [x] **Error Handling**: GovernanceError enum with comprehensive error types +- [ ] **Governance-as-Operator path**: Implement `GovernanceTransitionRequest` / `TransitionContext` / `GovernanceTransitionResult`, `evaluate_state_transition`, and resource-zome `request_resource_transition` +- [ ] **Governance-as-Operator completion**: Typed rule evaluation, consistent authorization, and automatic event/PPR generation --- ### Phase 2: Enhanced Governance & Process Integration 🚀 **HIGH PRIORITY** -#### 2.1 Enhanced Private Data Sharing (`zome_person`) 📋 **NEXT SPRINT** +#### 2.1 Enhanced Private Data Sharing (`zome_person`) 🔄 **PARTIAL** -_Building on existing private data infrastructure without breaking changes_ +_Field-level direct grants are implemented. The outstanding work is the request/approval ceremony, lifecycle visibility, auditing, and full workflow tests._ -- [ ] **Data Access Request System** (NEW): +- [ ] **Data Access Request System**: - [ ] `DataAccessRequest` entry type with status tracking - [ ] `request_private_data_access()` function for requesting specific fields - [ ] `respond_to_data_request()` function for approving/denying requests - [ ] Bidirectional linking system for request tracking -- [ ] **Data Access Grant System** (NEW): - - [ ] `DataAccessGrant` entry type with expiration and field control - - [ ] `grant_private_data_access()` function for direct grants - - [ ] `get_granted_private_data()` function for accessing granted data - - [ ] `revoke_data_access_grant()` function for revoking access -- [ ] **Governance Integration** (NEW): - - [ ] `get_private_data_for_governance_validation()` function for cross-zome access - - [ ] Agent promotion workflow integration with private data validation - - [ ] Enhanced role validation with identity verification - -#### 2.2 Economic Process Infrastructure (`zome_resource`) 📋 **CURRENT SPRINT** +- [x] **Direct Capability Grant Foundation**: + - [x] `PrivateDataCapabilityMetadata` with allowed fields, context, expiry, grantor/grantee, and local capability secret + - [x] Field filtering through `FilteredPrivateData` response views + - [x] Grant, claim, retrieval, revoke, owned-grant, role-based, and transferable grant APIs under their current names (`grant_private_data_access`, `get_private_data_with_capability`, `revoke_private_data_access`, etc.) + - [x] Governance-oriented private-data validation API +- [ ] **Grant Lifecycle Completion**: + - [ ] Enforce a true maximum grant duration; current callable grants accept arbitrary `expires_in_days` + - [ ] Remove mock/fallback retrieval paths and harden revocation discovery + - [ ] `get_expiring_grants()` for proactive renewal/expiry handling + - [ ] Auditable private-data access events + - [ ] End-to-end request→approval→access→revocation Sweettests +- [ ] **Governance Integration Completion**: + - [ ] Connect private-data eligibility checks to a real, queryable promotion-request workflow + - [ ] Replace specialized-role auto-approval with credential and approver validation + +#### 2.2 Economic Process Infrastructure (`zome_resource`) 📋 **HIGH PRIORITY** _Extending existing resource management with process-aware workflows. **NDO track overlap:** state split and discovery links map to REQ-NDO-LC-*, REQ-NDO-OS-*, REQ-NDO-OS-06; process and PPR linkage align with REQ-NDO-L2-* once Layer 2 is modeled via `NDOToProcess` (see [ndo_prima_materia.md §4.4](requirements/ndo_prima_materia.md))._ - [ ] **Economic Process Data Structures** (NEW): - [ ] `EconomicProcess` entry type with status tracking and role requirements - [ ] `ProcessStatus` enum (Planned, InProgress, Completed, Suspended, Cancelled, Failed) - - [ ] **Split `ResourceState` into `LifecycleStage` + `OperationalState`** (see ndo_prima_materia.md Section 5): - - [ ] `LifecycleStage` enum on `NondominiumIdentity` (Layer 0) — maturity/evolutionary phase - - [ ] `OperationalState` enum on `EconomicResource` (Layer 2) — current process condition (`Available`, `Reserved`, `InTransit`, `InStorage`, `InMaintenance`, `InUse`, `PendingValidation`) - - [ ] Update governance zome state transition logic to manage both enums independently - - [ ] Split `ResourcesByState` link type into `ResourcesByLifecycleStage` and `ResourcesByOperationalState` + - [x] **Split legacy `ResourceState` into `LifecycleStage` + `OperationalState`** (see ndo_prima_materia.md Section 5): + - [x] `LifecycleStage` enum on `NondominiumIdentity` (Layer 0) — 10 stages with integrity-validated transitions + - [x] `OperationalState` enum on `EconomicResource` — 7 process states; default `PendingValidation` on create + - [ ] Update governance zome state transition logic to manage both enums independently (REQ-NDO-OS-02/03 — deferred) + - [x] Add NDO lifecycle discovery through `NdoByLifecycleStage` + - [x] Replace legacy `ResourcesByState` with `ResourcesByOperationalState`; lifecycle discovery remains on Layer 0 - [ ] `OperationalState` transitions aligned with process outcomes (begin/end of transport, storage, maintenance processes) - [ ] **Process Management Functions** (NEW): - [ ] `initiate_economic_process()` with role-based access control @@ -218,42 +241,51 @@ _Extending existing resource management with process-aware workflows. **NDO trac - [ ] Governance zome integration for process validation and PPR generation - [ ] Private data coordination for custody transfers -#### 2.3 Private Participation Receipt (PPR) System (`zome_gouvernance`) 🌟 **MAJOR FEATURE** - -_Adding comprehensive reputation system on top of existing governance infrastructure_ - -- [ ] **PPR Data Structures** (NEW): - - [ ] `PrivateParticipationClaim` entry type (private entry) - - [ ] `ParticipationClaimType` enum with 16 claim categories - - [ ] `PerformanceMetrics` structure for quantitative assessment - - [ ] `CryptographicSignature` structure for bilateral authentication -- [ ] **PPR Management Functions** (NEW): - - [ ] `issue_participation_receipts()` for bi-directional PPR issuance - - [ ] `sign_participation_claim()` for cryptographic verification - - [ ] `validate_participation_claim_signature()` for authenticity validation - - [ ] `get_my_participation_claims()` for private receipt retrieval - - [ ] `derive_reputation_summary()` for privacy-preserving reputation calculation -- [ ] **Process Integration** (NEW): +#### 2.3 Private Participation Receipt (PPR) System (`zome_gouvernance`) 🔄 **PROTOTYPE IMPLEMENTED** + +_The private entry model, 16 categories, coordinator APIs, signature validation, and local summary calculation exist. The production milestone is authenticated bilateral coordination and automatic workflow integration._ + +- [x] **PPR Data Structures**: + - [x] `PrivateParticipationClaim` private entry type + - [x] `ParticipationClaimType` enum with 16 claim categories + - [x] `PerformanceMetrics`, `CryptographicSignature`, and `ReputationSummary` +- [x] **PPR Coordinator Prototype**: + - [x] `issue_participation_receipts()` + - [x] `sign_participation_claim()` + - [x] `validate_participation_claim_signature()` and enhanced validation variant + - [x] `get_my_participation_claims()` via DHT discovery links + - [x] `derive_reputation_summary()` from the calling agent's linked receipts +- [ ] **Bilateral Authentication Completion**: + - [ ] Remove the placeholder counterparty signature from initial issuance + - [ ] Complete a counterparty-authenticated signing exchange with replay/idempotency handling + - [ ] Eliminate DHT discovery links to private claim action hashes, or redefine the privacy model explicitly + - [ ] Add active multi-agent Sweettests for issuance, countersigning, validation, privacy, and summaries +- [ ] **Process Integration**: - [ ] Automatic PPR generation for all Commitment-Claim-Event cycles - [ ] Economic Process completion triggers specialized PPR categories - [ ] Agent promotion generates appropriate PPR types -#### 2.4 Complete Agent Capability Progression 🎯 **GOVERNANCE CRITICAL** +#### 2.4 Complete Agent Capability Progression 🔄 **GOVERNANCE CRITICAL** -_Implementing the full Simple → Accountable → Primary Accountable Agent progression_ +_Role entries, assignment APIs, promotion externs, and governance validation entry points exist. The request artifact and several authorization/credential checks remain incomplete._ -- [ ] **Enhanced Agent Promotion** (EXTEND existing `promote_agent_to_accountable`): - - [ ] Cross-zome coordination with governance validation - - [ ] Private data quality assessment for promotion eligibility +- [x] **Promotion Foundation**: + - [x] `PersonRole` entries and six predefined role variants + - [x] Promotion request/approval coordinator entry points + - [x] Cross-zome governance and private-data validation entry points +- [ ] **Enhanced Agent Promotion**: + - [ ] Replace the placeholder request hash with a queryable `RolePromotionRequest` + - [ ] Enforce authorization and private-data quality requirements end-to-end - [ ] Automatic PPR generation for promotion activities - [ ] Capability token progression (general → restricted → full) -- [ ] **Specialized Role Validation** (EXTEND existing role assignment): - - [ ] Enhanced role validation for Transport, Repair, Storage roles +- [ ] **Specialized Role Validation**: + - [ ] Replace current auto-approval with credential checks for Transport, Repair, and Storage - [ ] Primary Accountable Agent validation requirements - [ ] Role-specific PPR generation for validation activities -- [ ] **Cross-Zome Validation Workflows** (NEW): - - [ ] Resource validation during first access events - - [ ] Agent identity validation with private data verification +- [ ] **Cross-Zome Validation Workflow Completion**: + - [x] Resource/process/agent validation entry types and coordinator APIs + - [ ] Connect resource validation to first-access events + - [ ] Enforce agent identity validation with private data verification - [ ] Specialized role validation with existing role holder approval **Agent Ontology Items (Post-MVP, Phase 2 — see [requirements.md §4.4](requirements/requirements.md) and [archives/agent.md](archives/agent.md) §5.3; `REQ-AGENT-*`):** @@ -516,7 +548,7 @@ _Optimizing the system for large-scale network operation_ --- -## 5. Risk Mitigation +## 7. Risk Mitigation - **Cross-Zome Dependencies**: Mitigated by interface design and testing. - **Validation Complexity**: Addressed through modular validation functions. @@ -527,23 +559,25 @@ _Optimizing the system for large-scale network operation_ ## 8. Success Metrics & Implementation Tracking -### Phase 1 Achievements ✅ **FOUNDATION COMPLETE** +### Phase 1 Achievements ✅ **FOUNDATION DELIVERED** -- [x] **Person Management**: Complete agent identity system with public/private data separation -- [x] **Resource Management**: Full resource specification and economic resource lifecycle -- [x] **Governance Foundation**: Basic validation infrastructure and cross-zome functions +- [x] **Person Management Foundation**: Public/private identity, roles, capability metadata, Agent↔Person mapping, and devices +- [x] **Resource Management Foundation**: ResourceSpecification/EconomicResource CRUD plus NDO Layer 0 lifecycle +- [x] **Governance Foundation**: Validation infrastructure, EconomicEvents, and cross-zome validation helpers +- [ ] **Governance-as-Operator**: Request→Evaluate→Apply path and typed rule evaluation are still outstanding - [x] **Modular Architecture**: Clean separation of concerns across all three zomes -- [x] **Comprehensive Testing**: Foundation, integration, and scenario test coverage +- [x] **Active Sweettest suites**: Core Nondominium, Lobby, and Group DNA integration coverage +- [ ] **Coverage completion**: PPR, capability/device, promotion, ignored Agreement/Contribution, and partially stubbed governance workflows - [x] **Error Handling**: Robust error types and proper DHT signal handling ### Phase 2 Targets 🎯 **GOVERNANCE & PROCESSES** -- [ ] **Enhanced Private Data Sharing**: Request/grant workflows with time-limited grants (30-day maximum per capability metadata) and field-specific control +- [ ] **Enhanced Private Data Sharing**: Direct field-level grants are prototyped; complete request/approval, expiry enforcement, mock-path removal, audit, and workflow tests - [ ] **Economic Process Infrastructure**: Four structured processes (Use, Transport, Storage, Repair) with role-based access -- [ ] **PPR Reputation System**: Bi-directional Private Participation Receipts with cryptographic signatures +- [ ] **PPR Reputation System**: Prototype structures/APIs are implemented; complete authenticated bilateral exchange, privacy-model hardening, and automatic workflow issuance - [ ] **Agent Capability Progression**: Complete Simple → Accountable → Primary Accountable Agent advancement -- [ ] **Cross-Zome Integration**: Seamless coordination across person, resource, and governance zomes -- [ ] **Validation Workflows**: Resource validation, agent promotion, and specialized role validation operational +- [ ] **Cross-Zome Integration**: Implement and harden the Request→Evaluate→Apply Governance-as-Operator path +- [ ] **Validation Workflows**: Existing validation APIs must become fully authorized and connected to resource access, promotion, and specialized roles ### Phase 3 Targets 🔒 **PRODUCTION SECURITY** @@ -563,11 +597,13 @@ _Optimizing the system for large-scale network operation_ --- -## 7. UI Development Plan 🎨 +## 9. UI Development Plan 🎨 ### Current Frontend Status - **MVP UI**: ✅ Implemented — persistent Lobby sidebar + Group panel + NDO detail page with full NDO lifecycle management, Join NDO placeholder ("Coming soon"), **Associate with group** modal, multi-member group invites + DHT member lists + reactive join + idempotent membership self-heal (`ensureMembership`), pull-based reactivity for shared-group items (tab focus + gentle poll; `TODO(signals)` for push), fork friction modal, and reliable NDO data display via cache + DHT refresh +- **NDO tabs**: Resources, Governance, and Activity render current data; Composition remains a placeholder +- **PropertyRegime gap**: Rust defines six canonical regimes (`Private`, `Commons`, `Collective`, `Pool`, `CommonPool`, `Nondominium`); frontend shared types and controls currently expose only four and must be reconciled - **Stack**: SvelteKit 2 + Svelte 5 runes + TypeScript + UnoCSS + Melt UI next-gen + Effect-TS - **Dev runtime**: Browser (web) — `hc-spin`/Electron superseded by `scripts/launch-happ.mjs`, which runs one Vite dev server per agent on consecutive ports (`VITE_DEV_AGENT`-pinned), writes `ui/static/hc-connection.json`, and auto-opens a browser tab per agent (`NO_OPEN=1` to disable). See `ui_architecture.md §15` - **Service Layer**: ✅ Complete (PR #97 + MVP UI work) — all three zome services + NDO/Lobby services with Effect-TS `Context.Tag` / `Layer` / `E.gen` pattern @@ -579,32 +615,34 @@ _Optimizing the system for large-scale network operation_ - [x] **Effect-TS service layer**: All three zome services + NdoService + LobbyService (PR #97 + MVP UI) - [x] **HolochainClientService**: `wrapZomeCallWithErrorFactory` pattern, `Context.Tag` injection -### Phase 2: MVP UI — Lobby → Group → NDO ✅ **COMPLETE** +### Phase 2: MVP UI — Lobby → Group → NDO 🔄 **FOUNDATION IMPLEMENTED; GAPS TRACKED** Implements `documentation/requirements/ui_design.md` MVP section and reconciled requirements from GitHub Issue #102. Includes UI-restructure sprint that made the Lobby the persistent outer shell and fixed NDO data display. #### Foundation (initial delivery) -- [x] **Three-level identity model**: `LobbyUserProfile` (localStorage), `GroupMemberProfile` (localStorage), `Person` (DHT on first action) — `documentation/requirements/agent.md §2` -- [x] **Shared types**: `NdoInput`, `UpdateLifecycleStageInput`, `NdoTransitionHistoryEvent`, `LobbyUserProfile`, `GroupMemberProfile`, extended `GroupDescriptor` and `NdoDescriptor`; `PropertyRegime` reduced to 4 canonical variants (Private, Commons, Nondominium, CommonPool) — `packages/shared-types/src/resource.types.ts` +- [x] **Three-level identity model foundation**: `LobbyUserProfile` (localStorage), `GroupMemberProfile` (localStorage), and Person service/store wiring +- [ ] **First-action Person creation**: Enforce automatic `Person` creation on the agent's first DHT-active action in the UI flow +- [x] **Shared types foundation**: `NdoInput`, `UpdateLifecycleStageInput`, `NdoTransitionHistoryEvent`, `LobbyUserProfile`, `GroupMemberProfile`, extended `GroupDescriptor` and `NdoDescriptor` +- [ ] **PropertyRegime reconciliation**: Add `Collective` and `Pool` to frontend shared types, schemas, creation controls, filters, and display maps so all six canonical Rust variants are supported - [x] **NDO service methods**: `createNdo`, `updateLifecycleStage`, `getNdoTransitionHistory`, `getGroupNdoDescriptors`, `getLobbyNdoDescriptors` — `ndo.service.ts` - [x] **Resource service methods**: `createNdo`, `getNdo` (return type corrected to `NondominiumIdentity | null` matching Rust `Option`), `updateLifecycleStage`, filtered queries, history — `resource.service.ts` - [x] **Lobby/Group service (Group + Lobby DNA)**: `getMyGroups`, `createGroup` (clone cell → `create_group` → `join_group` → `announce_group`), `joinGroup` (clone cell + `is_member` guard + best-effort `join_group`, gossip-retry `fetchGroupProfileWithRetry` + invite-payload fallback for reactive sidebar; `TODO(signals)`), `ensureMembership` (idempotent membership self-heal so a joined agent always reconciles into the member list), `generateInviteLink`; only the Level 2 `GroupMemberProfile` stays in `localStorage` — `lobby.service.ts` (Group DNA backend complete, PR #107) - [x] **Shared-group pull reactivity**: `group.store.refreshCurrentGroup()` + `GroupView` tab-focus/visibility + gentle ~8 s poll keep members/NDOs fresh as peers' changes gossip in, without a manual reload; `loadGroupData` silent mode avoids flicker. Push upgrade tracked as `TODO(signals)` (`remote_signal` from `zome_group`) - [x] **app.context**: `lobbyUserProfile` state with localStorage hydration - [x] **lobby.store**: `activeFilters`, `filteredNdos`, `createGroup`, `joinGroup`; `loadLobby()` now invoked from root layout -- [x] **group.store**: `group`, `groupNdos`, `loadGroupData`, `createNdo`, **`associateNdoWithGroup`** (append spec hash to `GroupDescriptor.ndoHashes` in `localStorage`; `TODO` hook for Group DHT when DNA lands) +- [x] **group.store**: `group`, `groupNdos`, `members`, `loadGroupData`, `refreshCurrentGroup`, `createNdo`, and **`associateNdoWithGroup`** backed by Group-cell `SoftLink` entries - [x] **ndo-cache.ts** *(new)*: in-memory descriptor cache keyed by hash; populated on card click to seed NDO page instantly - [x] **UserProfileForm.svelte**: Lobby profile create/edit, modal + page modes, nickname required - [x] **GroupProfileModal.svelte**: Per-group disclosure preferences (first visit only) -- [x] **NdoBrowser.svelte**: Multi-select filter chips (LifecycleStage × ResourceNature × PropertyRegime 4 variants) +- [x] **NdoBrowser.svelte**: Multi-select filter chips (LifecycleStage × ResourceNature × PropertyRegime); currently covers four regimes - [x] **NdoCard.svelte**: Populates `ndo-cache` before navigating to NDO page - [x] **NdoCreateModal.svelte**: 5-field form (4-variant regime), uniqueness check, Effect-TS errors, navigation on success - [x] **NdoIdentityLayer.svelte**: Initiator profile link, lifecycle transition button (initiator-only), TransitionHistoryPanel; 4-variant regime color map - [x] **LifecycleTransitionModal.svelte**: Full state machine, Deprecated/Hibernating special cases - [x] **TransitionHistoryPanel.svelte**: Collapsible history panel with copy-to-clipboard - [x] **ForkNdoModal.svelte**: Informational fork friction modal, copy-pubkey CTA -- [x] **AssociateNdoModal.svelte**: multi-select modal of groups **not** already linked to this NDO; confirms via `associateNdoWithGroup` (see MVP ToDo in `ui_design.md` for DHT propagation) +- [x] **AssociateNdoModal.svelte**: multi-select modal of groups **not** already linked to this NDO; confirms via `associateNdoWithGroup`, which creates a Group-cell `SoftLink` #### UI-restructure sprint (persistent Lobby shell) @@ -613,14 +651,17 @@ Implements `documentation/requirements/ui_design.md` MVP section and reconciled - [x] **`LobbyView.svelte`** (simplified): removed GroupSidebar and onMount data loading; renders page header + NdoBrowser only; **`$effect` no longer assigns `appContext.currentView = 'lobby'`** (that clobbered the NDO route when both Lobby and NDO views were reactive); `currentView` is set where the routed page applies (e.g. `NdoView` sets `'ndo'`) - [x] **`GroupView.svelte`**: replaced `onMount` with `$effect` so group name and NDO list reload correctly when navigating between groups via the sidebar - [x] **`NdoView.svelte`** (extended): NDO detail card (Description, Property Regime, Resource Nature, Lifecycle Stage, Created); loading skeleton; retry-able error banner; Join NDO placeholder (inline "Coming soon"); **Associate with a group** (always visible header button → `AssociateNdoModal`); Fork button (Holochain + agent connected); descriptor seeded from `ndo-cache`, refreshed from DHT in background; **`$effect` that sets `selectedNdoId` must decode into a local `hash` variable** — assigning `selectedNdoId = specActionHash` immediately after mutating `$state(specActionHash)` created a self-referential dependency and **`effect_update_depth_exceeded`** (broken header buttons); fixed by passing the local `Uint8Array` reference only +- [x] **NDO data tabs**: Resources, Governance, and Activity render existing zome/service data +- [ ] **Composition tab**: Replace placeholder with hard-link/component/version graph data +- [ ] **Join NDO**: Implement backend membership and replace the current "Coming soon" UI - [x] **`/group/[id]` route**: `?createNdo=1` query param still supported - [x] **`/ndo/new` route**: redirects to active group or shows instruction screen ### Phase 3: Service Layer (Post-MVP) 🏗️ -- [ ] **PersonService extensions**: `DataAccessRequest` / `DataAccessGrant` workflows +- [ ] **PersonService extensions**: Expose existing capability-grant/device APIs and add the new `DataAccessRequest` approval workflow - [ ] **ResourceService**: Economic Process initiation + state management + custody transfers -- [ ] **GovernanceService**: PPR management + reputation calculation +- [ ] **GovernanceService**: Expose the existing PPR prototype APIs, then support the completed bilateral workflow - [ ] **ProcessService**: Economic Process lifecycle (initiate, track, complete, chain) - [ ] **ReputationService**: PPR retrieval + selective disclosure @@ -641,7 +682,7 @@ Implements `documentation/requirements/ui_design.md` MVP section and reconciled ### Phase 6: Group DNA Backend & Post-MVP UI 🌐 -- [x] **Group DNA backend** ✅ Complete (PR #107): cloned-cell `zome_group` (4 entry types, 15 coordinator externs, 13 Sweettest cases); `LobbyService`/`GroupService` now call the Group + Lobby DNAs directly (clone cells, `announce_group`, `get_my_group`, SoftLinks). Only the Level 2 `GroupMemberProfile` presentation choice remains in `localStorage` +- [x] **Group DNA backend** ✅ Complete for current scope (PR #107): cloned-cell `zome_group` (4 entry types, 16 coordinator externs, 13 Sweettest cases); `LobbyService`/`GroupService` call the Group + Lobby DNAs directly (clone cells, `announce_group`, `get_my_group`, SoftLinks). Only the Level 2 `GroupMemberProfile` presentation choice remains in `localStorage` - [ ] **Push reactivity via Holochain signals** (`TODO(signals)`): `zome_group` `remote_signal`s members on `join_group` / `create_soft_link` / `log_work`; UI refreshes `refreshCurrentGroup()` on those signals; the current pull layer (per-open reconcile + focus + poll) is kept only as an offline/missed-signal fallback. Design note in `dnas/group/zomes/coordinator/zome_group/src/lib.rs` - [ ] **NDO cell cloning**: Per-NDO DHT, once Holochain cloning stabilises - [ ] **Fork submission flow**: Claim, vote, and Unyt stake (after Unyt integration §12.2) @@ -653,16 +694,18 @@ Implements `documentation/requirements/ui_design.md` MVP section and reconciled ### Immediate Development Priorities (Next 6 Months) -- **Phase 2.1**: Enhanced private data sharing system implementation +- **Phase 2.1**: Complete private-data request/approval, expiry enforcement, mock-path removal, audit, and tests on the grant prototype - **Phase 2.2**: Economic Process infrastructure with four process types -- **Phase 2.3**: Private Participation Receipt system with reputation tracking -- **UI Phase 1-2**: Foundation UI with Economic Process and PPR support +- **Phase 2.3**: Complete authenticated bilateral PPR exchange, privacy-model hardening, and automatic issuance on the implemented prototype +- **Governance-as-Operator**: Implement the Request→Evaluate→Apply path, typed GovernanceRule evaluation, authorization hardening, and uniform event/PPR generation +- **UI**: Reconcile all six PropertyRegime variants, then add Economic Process and PPR workflows ### Medium-Term Enhancements (6-18 Months) - **Phase 3**: Production security with progressive capability tokens - **Phase 4.1**: Advanced process workflows and automation -- **NDO migration track** (when scheduled): L0-first resource creation, retroactive anchoring, capability slots — Section 12.1 and REQ-NDO-MIG-* +- **NDO migration track** (when scheduled): L0-first creation already exists; add retroactive anchoring for legacy specs, Layers 1/2 activation, operational state, and capability slots — Section 12.1 and REQ-NDO-MIG-* +- **Source-NDO application profile** (optional, when scheduled): Opt-in `SourceProfile`, boundary events, adaptive stewardship — Section 12.7; only for applications whose domain requires it; not a dependency for Project or resource-sharing deployments - **Cross-Network Integration**: Federated nondominium networks with PPR portability - **Mobile Interface**: Progressive Web App with full Economic Process support @@ -715,23 +758,32 @@ This enhanced implementation plan transforms the nondominium hApp from a foundat - Comprehensive error handling and rollback mechanisms across all zomes - Advanced validation schemes with reputation-weighted consensus and dispute resolution -This plan ensures the nondominium hApp will fulfill its vision of decentralized, commons-based resource management with sophisticated governance, Economic Process management, privacy-preserving reputation tracking, and embedded accountability, in alignment with [requirements.md](requirements/requirements.md) and, when scheduled, the NDO model in [ndo_prima_materia.md](requirements/ndo_prima_materia.md). +This plan ensures the nondominium hApp will fulfill its vision of decentralized, commons-based resource management with sophisticated governance, Economic Process management, privacy-preserving reputation tracking, and embedded accountability, in alignment with [requirements.md](requirements/requirements.md) and the remaining NDO work in [ndo_prima_materia.md](requirements/ndo_prima_materia.md). ### NDO track (when prioritized) -- Introduce L0/L1/L2 structures, migration, and capability surface without breaking existing MVP flows until migration windows are defined (REQ-NDO-MIG-*). +- Build from implemented Layer 0 into Layer 1/2 activation, legacy migration, and capability surfaces without breaking existing MVP flows (REQ-NDO-MIG-*). - Preserve governance-as-operator invariants while splitting lifecycle and operational dimensions (REQ-ARCH-07, REQ-NDO-LC-02, REQ-NDO-OS-02). +### Source-NDO application profile (optional — when domain requires it) + +- Implement as opt-in profile modules per REQ-SOURCE-APP-*; do not block Project NDO or resource-mutualisation delivery on Source phases (§12.7). +- Default hApp and UI remain Agent + Resource complete; ecological/knowledge-commons deployments enable the profile explicitly. + --- ## 12. Post-MVP design tracks (NDO, integrations, extensions) -**Status:** specified in documentation; **not** part of the MVP WASM deliverable until explicitly scheduled. Normative NDO requirements: [ndo_prima_materia.md](requirements/ndo_prima_materia.md) (§9 REQ-NDO-*, §10 migration). Integration stubs: [unyt-integration.md](requirements/post-mvp/unyt-integration.md), [flowsta-integration.md](requirements/post-mvp/flowsta-integration.md). Supplementary ontology context: [archives/resources.md](archives/resources.md), [archives/agent.md](archives/agent.md), [archives/governance.md](archives/governance.md). +**Status:** This section mixes implemented post-MVP foundations with unscheduled design tracks. Checked items are present in the current WASM/UI; unchecked items remain specifications until scheduled. Normative NDO requirements: [ndo_prima_materia.md](requirements/ndo_prima_materia.md) (§9 REQ-NDO-*, §10 migration). Integration stubs: [unyt-integration.md](requirements/post-mvp/unyt-integration.md), [flowsta-integration.md](requirements/post-mvp/flowsta-integration.md). Supplementary ontology context: [archives/resources.md](archives/resources.md), [archives/agent.md](archives/agent.md), [archives/governance.md](archives/governance.md). ### 12.1 Generic NDO (three-layer model, lifecycle split) -- [ ] Introduce `NondominiumIdentity` (Layer 0), `NDOToSpecification` / `NDOToProcess` / holonic links, capability slot surface — see [ndo_prima_materia.md](requirements/ndo_prima_materia.md) §§4, 8, 10. -- [ ] Split `ResourceState` into `LifecycleStage` + `OperationalState`; split discovery links (`REQ-NDO-OS-06`) — detailed in Phase 2.2 (Section 5); align with prima materia §5 / §9.4. +- [x] Implement `NondominiumIdentity` Layer 0 with permanent identity, six `PropertyRegime` variants, five `ResourceNature` variants, lifecycle metadata, and validated updates. +- [x] Implement `LifecycleStage` and Layer 0 discovery facets (`NdoByLifecycleStage`, `NdoByNature`, `NdoByPropertyRegime`). +- [ ] Add `NDOToSpecification`, `NDOToProcess`, holonic links beyond the implemented federation primitives, and the `CapabilitySlot` surface. +- [x] Replace legacy `ResourceState` with `OperationalState` on `EconomicResource` and `ResourcesByOperationalState` discovery (`REQ-NDO-OS-01`, `REQ-NDO-OS-06`). +- [ ] Integrate lifecycle transitions with Governance-as-Operator, required EconomicEvents, role authorization, and EndOfLife challenge periods. +- [ ] Implement retroactive anchoring/migration for legacy ResourceSpecifications (REQ-NDO-MIG-*). ### 12.2 Unyt integration (three phases, parallel to prima materia §6.6) @@ -758,7 +810,8 @@ High-level ordering and dependencies (detailed requirements live in each file): - **[digital-resource-integrity.md](requirements/post-mvp/digital-resource-integrity.md):** Content-addressed manifests and hierarchical verification — attach via Layer 1 **DigitalAsset** capability slots (prima materia §9.2); aligns with distributed storage expectations for specs. - **[resource-transport-flow-protocol.md](requirements/post-mvp/resource-transport-flow-protocol.md):** Multi-dimensional transport and flow semantics — builds on mature **EconomicEvent** metadata and process modeling; cross-link to operational state and RTP-style location/custody dimensions. - **[valueflows-dsl.md](requirements/post-mvp/valueflows-dsl.md):** Scriptable network bootstrap and recipe definition — operational tooling; depends on stable VF entry types and governance evaluation surfaces in the DNA. -- **[lobby-dna.md](requirements/post-mvp/lobby-dna.md):** Multi-network federation — see §12.6 below. +- **[source-ndo-requirements.md](requirements/post-mvp/source-ndo-requirements.md):** Optional `Source` application profile; progressive activation per REQ-SOURCE-APP-* — see §12.7; PRD anchor [requirements.md §4.6](requirements/requirements.md) +- **[lobby-dna.md](requirements/post-mvp/lobby-dna.md):** Federation foundation is implemented; remaining Moss, push-signal, per-NDO-cell, and integration work is tracked in §12.6. ### 12.6 Lobby DNA — multi-network federation @@ -767,23 +820,105 @@ Architecture: [specifications/post-mvp/lobby-architecture.md](specifications/pos Two implementation sub-scopes with different delivery ordering: -**New DNAs (Lobby + Group) — plan after NDO governance-as-operator stabilizes:** -- [ ] Lobby DNA: `zome_lobby_integrity` + `zome_lobby_coordinator` — `LobbyAgentProfile`, `NdoDescriptor`, faceted discovery links -- [ ] Group DNA: `zome_group_integrity` + `zome_group_coordinator` — `GroupDescriptor`, `GroupMembership`, `WorkLog`, `SoftLink`, `GroupGovernanceRule` -- [ ] `happ.yaml` roles: `lobby` (fixed `network_seed: "nondominium-lobby-v1"`), `group` (cloning_limit 255), `nondominium` (cloning_limit 1024) +**Implemented federation foundation:** +- [x] Lobby DNA: `zome_lobby_integrity` + `zome_lobby_coordinator` — `LobbyAgentProfile`, `GroupAnnouncement`, discovery/update links, 9 coordinator externs, and 5 Sweettest scenarios +- [x] Group DNA: isolated cloned cells with `GroupProfile`, `GroupMembership`, `WorkLog`, and `SoftLink`; 16 coordinator externs and 13 Sweettest scenarios +- [x] `happ.yaml` roles for fixed Lobby, core Nondominium, bundled hREA, and deferred Group cloning (`clone_limit: 64`) +- [x] Frontend Group clone provisioning, invites, Lobby announcement, DHT membership reconciliation, SoftLink-based NDO association, and pull reactivity +- [x] `NdoHardLink` entry type + `NdoToHardLinks` / `HardLinkByType` link types — immutable, requires valid EconomicEvent fulfillment (REQ-NDO-EXT-01–06) + - *Stage 2 (pre-Lobby, single cell):* `to_ndo_dna_hash` equals the shared DNA hash (same cell for source and target). *Stage 3 (per-NDO clone):* `to_ndo_dna_hash` is the target cell's unique hash. Same struct, no breaking change. See lobby-architecture.md §6.1. +- [x] `Contribution` entry type + `NdoToContributions` / `AgentToContributions` / `ContributionToEvent` link types — peer-validated Work/Modify contributions (REQ-NDO-EXT-07–11) +- [x] `Agreement` entry type + `NdoToAgreement` / `AgreementUpdates` link types — versioned benefit-redistribution clauses (REQ-NDO-EXT-12–16) +- Note: federation Sweettests are partial — hard-link coverage is active; Agreement and Contribution scenarios are currently ignored. + +**Remaining federation work:** +- [ ] Push reactivity through Group `remote_signal`, retaining focus/poll as an offline fallback - [ ] Moss WeApplet contract (`ui/src/we-applet.ts`) — `search`, `getAssetInfo`, `openAsset` +- [ ] Per-NDO cloned cells and cross-cell hard-link operation when that deployment model is adopted +- [ ] Full version DAG and upstream contribution/benefit propagation +- [ ] Unyt activation of monetary Agreement clauses and Flowsta cross-app identity mapping +- [ ] Activate ignored Agreement/Contribution Sweettests and any missing AccountableAgent setup they require -**NDO DNA extensions (zome_gouvernance) — plan after Governance-as-Operator (#41–#44) lands:** -- [ ] `NdoHardLink` entry type + `NdoToHardLinks` / `HardLinkByType` link types — immutable, requires AccountableAgent + valid EconomicEvent fulfillment (REQ-NDO-EXT-01–06) - - *Stage 2 (pre-Lobby, single cell):* `to_ndo_dna_hash` equals the shared DNA hash (same cell for source and target). *Stage 3 (per-NDO clone):* `to_ndo_dna_hash` is the target cell's unique hash. Same struct, no breaking change. See lobby-architecture.md §6.1. -- [ ] `Contribution` entry type + `NdoToContributions` / `AgentToContributions` / `ContributionToEvent` link types — requires at least one AccountableAgent validator (REQ-NDO-EXT-07–11) -- [ ] `Agreement` entry type (VF: `vf:Agreement`) + `NdoToAgreement` / `AgreementUpdates` link types — versioned, AccountableAgent-controlled (REQ-NDO-EXT-12–16) +**Dependencies for the remaining work:** +- Implementation of Governance-as-Operator Request→Evaluate→Apply for uniform typed rule and authorization checks +- Unyt integration (§12.2) for monetary Agreement execution +- Flowsta Phase 3 (§12.3) for cross-app identity attestations (REQ-LOBBY-INT-01) + +### 12.7 Source-NDO — optional generative-commons application profile (post-MVP) + +Normative requirements: [source-ndo-requirements.md](requirements/post-mvp/source-ndo-requirements.md) (REQ-SOURCE-*); applicability and UI gating: [requirements.md §4.6](requirements/requirements.md) (REQ-SOURCE-APP-01 – -04, REQ-UI-SOURCE-*). Academic grounding: [source-ndo-paper.md](requirements/post-mvp/source-ndo-paper.md). Sibling NDO type (no Source required): [project-type-ndo-specifications.md](requirements/post-mvp/project-type-ndo-specifications.md). + +**Profile boundary (dynamic complexity matching):** The generic NDO baseline is **Agent + Resource**. Source is an **opt-in application profile**, not a mandatory third primitive in every hApp or NDO UI. Communities enable it only when coordination must govern a generative system's condition, boundary flows, regeneration, or assimilation capacity. + +| Normally **enable** Source | Normally **do not** enable Source | +|---|---| +| Governance targets a resource *system* (watershed, river, fishery) not just appropriable units | Project NDO coordinating open-hardware design — Agents + Resources suffice | +| Extraction, loading, or regeneration must be visible on-ledger against the system | Mature-resource mutualisation (e.g. shared 3D printer) — custody, access, maintenance, Resource events suffice | +| Adaptive stewardship must respond to accumulated condition signals | No generative Source boundary is being governed (provenance from nature alone ≠ Source activation) | + +**REQ-SOURCE-APP checklist (implementation):** + +- [ ] **Profile flag / membrane config**: Application or DNA profile declares Source support enabled (REQ-SOURCE-APP-01) +- [ ] **Complexity-matched code paths**: Default flows complete with Agent/Resource only; Source zome modules and APIs load only when profile is on (REQ-SOURCE-APP-02, REQ-SOURCE-APP-04) +- [ ] **No universal UI burden**: Default `REQ-UI-NDO-01` creation form and Project/resource detail views unchanged when profile is off — no Source type selectors, regime panels, or steward workflows (REQ-SOURCE-APP-03, REQ-UI-SOURCE-01) + +**Problem addressed (when profile is on):** ValueFlows models **Agent** and **Resource**. A watershed, river, forest, or knowledge commons fits neither honestly — forcing a river into `EconomicResource` implies ownership (`primaryAccountable`); avoiding it hides depletion via `raise`; typing it as `Agent` for pollution receivers imports false agency. **`Source`** is the third flow endpoint for those domains only: generative, non-ownable, partially unknowable systems that yield resources, absorb effects, and carry adaptive governance. + +**Ostrom / SES mapping (operationalised):** + +| SES concept | Source-NDO | +|---|---| +| Resource system | **Source** (`SourceProfile` on Layer 0) | +| Resource unit | **`EconomicResource`** | +| Governance system | `GovernanceRule` + adaptive loop (requirements §6.6) | +| Users / actors | **Agents** (+ **`Steward`** functional role, profile-only) | + +**Layer model:** Same three layers as all NDOs. Layer 0 = `NondominiumIdentity` + linked **`SourceProfile`**. Layer 1 = **`SourceSpecification`**. Layer 2 = boundary **EconomicEvents**, commitments, claims, PPRs. **`property_regime`** SHALL be **`Nondominium`** or **`CommonPool`** only (REQ-SOURCE-ONT-02, REQ-SOURCE-GOV-02). + +**ValueFlows extension:** Add **`vf:Source`** in Source-enabled applications so flows may originate from and terminate in Sources (REQ-SOURCE-EVENT-01 – -03). + +**Adaptive governance loop** (profile Phase C+; beyond static rule evaluation): + +```text +boundary events → ledger on Source L0 hash → ecological interpretation + → governance rule revision → access affordances → conditioned future events +``` + +Black-box stance: govern observable boundary signals and `SourceRegimeState` transitions; do not model ecological interiors (REQ-SOURCE-GOV-01 – -08). + +**Implementation phasing** (from [source-ndo-requirements.md §9](requirements/post-mvp/source-ndo-requirements.md); all phases assume profile enabled): + +| Phase | Deliverable | Depends on | +|---|---|---| +| **A — Data model** | `SourceProfile`, `SourceType`, `SourceRegimeState`, `SourceCouplingLink`; Layer 0 ↔ SourceProfile link; **`Steward`** role (profile-only) | NDO Layer 0 ✅; REQ-SOURCE-APP-04 | +| **B — Boundary events** | `vf:Source` on `EconomicEvent`; extraction, loading, use, regeneration; governance-validated stock/assimilation updates | Phase A; `VfAction` vocabulary ✅ | +| **C — Adaptive governance** | Access-affordance rules; `SourceRegimeState` transitions; precautionary block at `tipping_threshold`; monitoring-obligation `GovernanceRule` type | **Governance-as-Operator** ❌; Phase B | +| **D — Layer 1 value + PPR** | Ecological value vector on `SourceSpecification`; stewardship PPR categories | PPR prototype 🔄; Phase C | +| **E — Federation** | Cross-DNA source hierarchies; federation-level source governance | Lobby/Group/federation ✅; Phase C | + +**Zome touchpoints (profile-only modules — do not alter default Agent/Resource paths):** + +- **`zome_resource`**: `SourceProfile`, coupling links, opt-in Source-NDO creation API (separate from generic `create_ndo`) +- **`zome_gouvernance`**: Source-as-provider/receiver on `EconomicEvent`; regime-driven evaluation; ledger queries by Source L0 hash +- **`zome_person`**: `Steward` in `RoleType` when profile enabled (REQ-SOURCE-GOV-07) + +**UI (Source-enabled applications only — REQ-UI-SOURCE-*):** + +- [ ] Distinct Source-NDO creation variant (`Nondominium` / `CommonPool`, `SourceType`, stewards); generic form unchanged when profile off +- [ ] Source detail panels (regime state, condition indicators, stewards, boundary-event history) — omitted from Project/resource mutualisation views +- [ ] Source hierarchy / coupling visualization (Composition tab extension, profile apps) +- [ ] Steward dashboard (monitoring obligations, regime transitions, access-affordance proposals) + +**REQ traceability:** REQ-SOURCE-APP-01 – -04 (profile), REQ-SOURCE-ONT-01 – -04, REQ-SOURCE-DATA-01 – -03, REQ-SOURCE-GOV-01 – -08, REQ-SOURCE-EVENT-01 – -03, REQ-USER-ST-01 – -09, REQ-UI-SOURCE-01 – -04. Does not modify REQ-NDO-* invariants or require existing NDOs to migrate. **Dependencies:** -- Lobby + Group DNAs: NDO Layer 0 complete ✅, Sweettest patterns established ✅ -- NDO DNA extensions: Governance-as-Operator (#41–#44) for AccountableAgent cross-zome role check -- Unyt integration (§12.2) activates `Agreement.clauses` with `BenefitType::Monetary` -- Flowsta Phase 3 (§12.3) replaces `GroupMembership.ndo_pubkey_map` with `IsSamePersonEntry` attestations (REQ-LOBBY-INT-01) + +- NDO Layer 0 and lifecycle facets ✅ +- Governance-as-Operator Request→Evaluate→Apply path ❌ (blocks full Phase C) +- Typed `GovernanceRule` evaluation ❌ +- PPR authenticated bilateral workflow ❌ (Phase D) +- Six-regime `PropertyRegime` UI parity 🔄 (Source variant needs `Nondominium` / `CommonPool` when profile on) +- **Explicit non-dependency:** Project NDO track, resource mutualisation, and MVP UI completion do **not** require Source phases A–E --- diff --git a/documentation/requirements/ndo_prima_materia.md b/documentation/requirements/ndo_prima_materia.md index 0adcd73..f41d88c 100644 --- a/documentation/requirements/ndo_prima_materia.md +++ b/documentation/requirements/ndo_prima_materia.md @@ -46,7 +46,7 @@ That model is well-grounded in the ValueFlows standard and works well for resour - **Layers 1 & 2 not activated:** `ResourceSpecification`, `EconomicResource`, and process entries are not yet linked to Layer 0 via `NDOToSpecification` or `NDOToProcess`. Legacy resource specs can still exist without an NDO parent; specification assets are not yet attached via `DigitalAsset` capability slots (REQ-NDO-L1-06). - **Specification richness:** Structured project-type know-how bundles ([`post-mvp/project-type-ndo-specifications.md`](post-mvp/project-type-ndo-specifications.md)) are post-MVP requirements only — the MVP `ResourceSpecification` entry remains a thin summary (name, description, category, tags). -- **`ResourceState` conflation:** On `EconomicResource`, the `ResourceState` enum (`PendingValidation`, `Active`, `Maintenance`, `Retired`, `Reserved`) still mixes lifecycle maturity with transient operational conditions. The split into `LifecycleStage` (on identity) + `OperationalState` (on instance) defined in Section 5 is not yet implemented in code (REQ-NDO-OS-01). +- **`ResourceState` conflation:** ~~On `EconomicResource`~~ **Resolved (data layer):** `EconomicResource.operational_state` uses `OperationalState`; lifecycle maturity lives on `NondominiumIdentity.lifecycle_stage`. Governance-zome transition ownership (REQ-NDO-OS-02/03) remains deferred. - **Governance-as-operator for lifecycle:** MVP allows only the NDO `initiator` to call `update_lifecycle_stage`. Governance-validated transitions, role authorization per Section 5.3, and automatic `EconomicEvent` generation on each transition (REQ-NDO-LC-02, REQ-NDO-LC-03) remain deferred. The three-layer prima materia model closes the original gap **progressively**: Layer 0 addresses identity and lifecycle *becoming*; Layers 1 (form) and 2 (process) will complete the model when linked and enriched as specified in Sections 4 and 9. @@ -365,9 +365,9 @@ graph TD ## 5. Resource State Model: Two Orthogonal Dimensions -> **Implementation snapshot (MVP):** `LifecycleStage` **is implemented** on `NondominiumIdentity` (10 stages, integrity-validated transitions, initiator-only authorization in the coordinator). `OperationalState` **is not yet implemented** — `EconomicResource` still uses the conflated `ResourceState` enum (`PendingValidation`, `Active`, `Maintenance`, `Retired`, `Reserved`). The split described below remains the **target architecture**. +> **Implementation snapshot (MVP):** `LifecycleStage` **is implemented** on `NondominiumIdentity` (10 stages, integrity-validated transitions, initiator-only authorization in the coordinator). `OperationalState` **is implemented** on `EconomicResource` (7 states, custodian-initiated updates via `update_operational_state`, faceted discovery via `ResourcesByOperationalState`). Governance-zome ownership of operational transitions (REQ-NDO-OS-02/03) remains deferred. -The current `ResourceState` enum conflates two independent dimensions of a resource's state. The NDO requires their explicit separation: +The legacy `ResourceState` enum conflated two independent dimensions. The NDO requires their explicit separation: - **`LifecycleStage`** — the maturity or evolutionary phase of the resource as an artefact. Advances rarely and (mostly) irreversibly, driven by significant events (design completion, peer validation, fabrication, end-of-life declaration). Lives on the `NondominiumIdentity` (Layer 0). - **`OperationalState`** — what process is currently acting on a specific resource instance. Cycles frequently as processes begin and end. Managed by the governance zome. Lives on the `EconomicResource` instance (Layer 2). @@ -489,7 +489,7 @@ stateDiagram-v2 ### 5.4 OperationalState Enum -> **Status:** ❌ **Not implemented.** `EconomicResource.state` still uses `ResourceState`. See REQ-NDO-OS-01 through REQ-NDO-OS-06 and the TODO in `zome_resource` `LinkTypes::ResourcesByState`. +> **Status:** ✅ **Implemented (data layer).** `EconomicResource.operational_state` uses `OperationalState`. `ResourcesByOperationalState` replaces legacy `ResourcesByState`. Lifecycle faceting remains on `NdoByLifecycleStage` (Layer 0). Governance-zome transition rules (REQ-NDO-OS-02/03) remain deferred. Lives on `EconomicResource` (Layer 2). Describes *what process is currently acting on a specific resource instance*. Set and cleared by the governance zome when processes begin and end. @@ -1284,7 +1284,7 @@ Normative requirements below remain valid as design targets. Status reflects the | Layer 0 (`NondominiumIdentity`, discovery, lifecycle validation) | ✅ MVP (#80) | Initiator-only transitions; optional `NdoToTransitionEvent` | | Layer 1 activation (`NDOToSpecification`) | ❌ Post-MVP | Legacy `ResourceSpecification` exists unlinked | | Layer 2 activation (`NDOToProcess`) | ❌ Post-MVP | Governance events exist unlinked to NDO identity | -| `OperationalState` split | ❌ Post-MVP | `ResourceState` still conflated on `EconomicResource` | +| `OperationalState` split | ✅ Data layer | `operational_state` on `EconomicResource`; `ResourcesByOperationalState`; governance-operator transitions deferred | | Governance-as-operator lifecycle (REQ-NDO-LC-02/03/07) | 🔄 Partial | Integrity validation only; no role-gated governance zome path | | `CapabilitySlot` surface (`zome_resource`) | ❌ Post-MVP | Unyt / Flowsta slot types specified, not coded | | Federation (`NdoHardLink`, `Contribution`, `Agreement`) | ✅ MVP (#103) | `zome_gouvernance`; distinct from CapabilitySlot | @@ -1329,7 +1329,7 @@ Legend: ✅ implemented · 🔄 partial · ❌ not started #### LifecycleStage Requirements -- **REQ-NDO-LC-01** ✅: The system shall implement the `LifecycleStage` enum as defined in Section 5.1 on the `NondominiumIdentity` entry. The legacy `ResourceState` enum on `EconomicResource` remains until REQ-NDO-OS-01 lands (see Section 10.3 migration map). +- **REQ-NDO-LC-01** ✅: The system shall implement the `LifecycleStage` enum as defined in Section 5.1 on the `NondominiumIdentity` entry. The legacy `ResourceState` enum on `EconomicResource` has been replaced by `OperationalState` (REQ-NDO-OS-01). - **REQ-NDO-LC-02** 🔄: Lifecycle stage transitions shall be validated by the governance zome acting as state transition operator, consistent with `REQ-ARCH-07` (governance-as-operator). MVP: integrity zome validation + initiator-only coordinator. - **REQ-NDO-LC-03** 🔄: Each lifecycle transition shall generate a corresponding `EconomicEvent` with the triggering `VfAction`, creating an auditable lifecycle history. MVP: optional `transition_event_hash` link; automatic event generation deferred. - **REQ-NDO-LC-04** ✅: The `Hibernating` stage shall be clearly distinguished from `Deprecated` and `EndOfLife`. A hibernating resource may be reactivated; deprecated and end-of-life resources may not be reactivated. @@ -1339,16 +1339,16 @@ Legend: ✅ implemented · 🔄 partial · ❌ not started #### OperationalState Requirements -> **Status:** ❌ All REQ-NDO-OS-* not started. +> **Status:** ✅ REQ-NDO-OS-01 and REQ-NDO-OS-06 implemented (data layer). REQ-NDO-OS-02 through REQ-NDO-OS-05 (governance-operator enforcement) remain deferred. -- **REQ-NDO-OS-01** ❌: The system shall implement the `OperationalState` enum as defined in Section 5.4 on the `EconomicResource` entry, replacing the process-related dimension of the current `ResourceState` enum. +- **REQ-NDO-OS-01** ✅: The system shall implement the `OperationalState` enum as defined in Section 5.4 on the `EconomicResource` entry, replacing the process-related dimension of the legacy `ResourceState` enum. - **REQ-NDO-OS-02**: `OperationalState` transitions shall be managed exclusively by the governance zome. The resource zome stores the field; only the governance zome may initiate valid transitions. - **REQ-NDO-OS-03**: Each `OperationalState` transition shall correspond to an open or completed `EconomicEvent`. The governance zome shall reject state transitions for which no corresponding event exists. - **REQ-NDO-OS-04**: `OperationalState` and `LifecycleStage` are orthogonal. An `OperationalState` transition shall never cause a `LifecycleStage` transition, and vice versa. - **REQ-NDO-OS-05**: The `InTransit`, `InStorage`, and `InMaintenance` states may occur at any `LifecycleStage` at or after `Development`. The system shall not restrict these states to any specific lifecycle stage. -- **REQ-NDO-OS-06**: The `ResourcesByState` link type shall be split into `ResourcesByLifecycleStage` and `ResourcesByOperationalState` to enable independent faceted queries on each dimension. +- **REQ-NDO-OS-06** ✅: The legacy `ResourcesByState` link type is replaced by `ResourcesByOperationalState` for EconomicResource faceted queries. Lifecycle faceting remains on `NdoByLifecycleStage` (Layer 0). -> **TODO (code)**: Split the current `ResourceState` enum in `zome_resource` integrity into `LifecycleStage` (on `NondominiumIdentity`) and `OperationalState` (on `EconomicResource`). Update `EconomicResource` struct, governance zome state transition logic, `ResourcesByState` link type, and all coordinator functions. See Section 10.3 for the migration map. +> **Note (code)**: Governance zome state transition logic for operational states (REQ-NDO-OS-02/03) remains a follow-up. See Section 10.3 for the legacy migration map. ### 9.5 Capability Surface Requirements @@ -1374,7 +1374,7 @@ Legend: ✅ implemented · 🔄 partial · ❌ not started - **REQ-NDO-MIG-01**: All new resources created after the introduction of the NDO model shall begin with a `NondominiumIdentity` creation as their first action. - **REQ-NDO-MIG-02**: Existing `ResourceSpecification` entries created before the NDO model shall be retroactively anchored to a new `NondominiumIdentity` entry. This operation shall be additive (no existing entries are modified or deleted). -- **REQ-NDO-MIG-03**: The `ResourceState` enum shall be deprecated and replaced by `LifecycleStage`. Existing records using `ResourceState` values shall be mapped using the migration table in Section 10.2 without data loss. +- **REQ-NDO-MIG-03** ✅: The legacy `ResourceState` enum is replaced by `OperationalState` on `EconomicResource` and `LifecycleStage` on `NondominiumIdentity`. Retroactive anchoring of legacy records (Phase 2) still uses the migration table in Section 10.3. - **REQ-NDO-MIG-04**: Existing `EconomicResource` entries shall not require migration. They shall be linked to the new NDO model via Layer 2 process links when the NDO is retroactively created. - **REQ-NDO-MIG-05**: The migration shall be implemented as a one-time migration coordinator function, not as a permanent API change, to avoid polluting the steady-state code with migration logic. @@ -1408,9 +1408,8 @@ ResourceSpecification (zome_resource) ↓ SpecificationToResource EconomicResource (zome_resource) - custodian: AgentPubKey - - state: ResourceState { PendingValidation, Active, Maintenance, Retired, Reserved } - ↑ TODO: split into OperationalState on EconomicResource (REQ-NDO-OS-06); - LifecycleStage now lives on NondominiumIdentity (Track A) + - operational_state: OperationalState { PendingValidation, Available, Reserved, InTransit, InStorage, InMaintenance, InUse } + ↑ LifecycleStage lives on NondominiumIdentity (Track A); governance-zome transition rules (REQ-NDO-OS-02/03) deferred GovernanceRule (zome_resource) (linked from ResourceSpecification via SpecificationToGovernanceRule) @@ -1460,7 +1459,7 @@ graph LR |---|---|---|---| | `ResourceSpecification` | Layer 1 (`ResourceSpecification`) | No structural change | Gains `NDOToSpecification` link from Layer 0 | | `EconomicResource` | Layer 2 artifact (resource instance) | No structural change | Linked via Process, not directly to NDO | -| `ResourceState` enum | `LifecycleStage` + `OperationalState` enums | Split replacement | See migration map below — each variant maps to one of the two new enums | +| Legacy `ResourceState` enum | `LifecycleStage` + `OperationalState` enums | ✅ Split complete (data layer) | See migration map below — governance-operator enforcement deferred (REQ-NDO-OS-02/03) | | `GovernanceRule` | Layer 1 asset | No structural change | Still linked from `ResourceSpecification` | | `EconomicEvent` | Layer 2 component | No structural change | Now linked through Process entry | | `Commitment` / `Claim` | Layer 2 components | No structural change | Now linked through Process entry | @@ -1472,9 +1471,9 @@ graph LR | *(none)* | `LifecycleStage` transitions | **New** | Governed by zome_gouvernance (maturity dimension) | | *(none)* | `OperationalState` transitions | **New** | Governed by zome_gouvernance (process dimension) | -### 10.3 ResourceState Migration Map +### 10.3 Legacy ResourceState Migration Map -The current `ResourceState` enum is split across the two new orthogonal dimensions. Each existing variant maps to a `(LifecycleStage, OperationalState)` pair: +Historical `ResourceState` values (pre-split) map to the two orthogonal dimensions. Each legacy variant maps to a `(LifecycleStage, OperationalState)` pair: | Current `ResourceState` | → `LifecycleStage` | → `OperationalState` | Migration notes | |---|---|---|---| @@ -1493,18 +1492,18 @@ The migration is **strictly additive** — no existing entries are modified or d **Phase 1 — Forward compatibility** *(partially complete)*: - ✅ New NDOs created via `create_ndo` begin with `NondominiumIdentity` (Group-scoped UI) - ❌ `NDOToSpecification` and `NDOToProcess` link types not yet added -- ✅ `LifecycleStage` on `NondominiumIdentity`; ❌ `OperationalState` split not yet done -- ❌ `ResourcesByState` not yet split into lifecycle vs operational facets +- ✅ `LifecycleStage` on `NondominiumIdentity`; ✅ `OperationalState` on `EconomicResource` (REQ-NDO-OS-01) +- ✅ `ResourcesByOperationalState` replaces legacy `ResourcesByState` (REQ-NDO-OS-06) **Phase 2 — Retroactive anchoring (migration coordinator):** - For each existing `ResourceSpecification` entry, create a `NondominiumIdentity` entry and the corresponding `NDOToSpecification` link - The `NondominiumIdentity` is created by the original author of the `ResourceSpecification` (or by a designated migration agent) -- Map the existing `ResourceState` to `(LifecycleStage, OperationalState)` pairs using the migration table in Section 10.3 +- Map legacy pre-split state values to `(LifecycleStage, OperationalState)` pairs using the migration table in Section 10.3 - Link existing `EconomicResource` instances to the new NDO via a retroactive Process entry **Phase 3 — Cleanup (optional, post-migration):** -- Deprecate the `ResourceState` enum in code (keep for deserialization compatibility of existing DHT entries) -- Update the UI to show `LifecycleStage` and `OperationalState` vocabulary separately +- ✅ `ResourceState` removed from code; `OperationalState` on `EconomicResource` (no production DHT back-compat shim) +- Update the UI to show `LifecycleStage` and `OperationalState` vocabulary separately (partial — NDO lifecycle UI done; economic-resource operational badges in ResourcesTab) - Activate capability slots for resources that have associated external assets **What is not required:** diff --git a/documentation/requirements/requirements.md b/documentation/requirements/requirements.md index e46cbf9..6dd2ef2 100644 --- a/documentation/requirements/requirements.md +++ b/documentation/requirements/requirements.md @@ -8,6 +8,8 @@ The project's central goal is to support a true sharing economy, overcoming the Built on the Holochain framework and using the ValueFlows standard, nondominium allows any Agent to interact with these Resources in a permissionless but accountable environment, with automatic reputation tracking through Private Participation Receipts (PPRs). +**Optional post-MVP economic ontology:** The universal NDO baseline models ValueFlows' **Agent** and **Resource** primitives. Applications whose domain includes generative, non-ownable systems may progressively activate **`Source`** as a third category (watersheds, rivers, forests, fisheries, knowledge commons) that yields Resources, receives ecological effects, and carries adaptive stewardship governance. Source is not required for ordinary Project NDOs or resource-mutualisation applications. Sources are **not** owned `EconomicResource` instances and **not** intentional Agents. Normative detail: [source-ndo-requirements.md](post-mvp/source-ndo-requirements.md) (REQ-SOURCE-*); implementation phasing: [implementation_plan.md](../implementation_plan.md) §12.7. + ## 2. Objective & Goals ### 2.1 Main Objective @@ -24,7 +26,7 @@ Develop a new class of Resources that are: - **Credentials and Reputation-enabled**: Built-in accountability through cryptographically-signed participation tracking - **Process-aware**: Supporting structured Economic Processes (Use, Transport, Storage, Repair) - **Fully specified**: Machine readable in terms of function, design architecture, standards (dimensions, tolerances, quality), etc. -- **Composable**: Resources can be combined into come complex resources, allow fork and remix +- **Composable**: Resources can be combined into complex resources, allow fork and remix - **Hard to Clone**: Governance, set of rules and incentives to make unnecessary copying of a resource unlikely. - **Lifecycle Managed**: Resources have managed lifecycles from creation through validation to end-of-life. - **Traceable**: Full provenance and economic activity tracking, affiliation to component resources @@ -38,24 +40,27 @@ Develop a new class of Resources that are: 4. **Identity and Role System**: Develop Agent identity infrastructure supporting pseudonymity, credentials, and private entry identification 5. **Reputation System**: Implement Private Participation Receipts (PPRs) for trustworthy, cumulative reputation tracking 6. **Process Management**: Support structured Economic Processes with role-based access control +7. **Ecological and knowledge commons (optional post-MVP profile)**: Where an application's domain actually includes a generative system, activate `Source` / Source-NDO so boundary events (extraction, loading, restoration) are recorded on-ledger and govern adaptive access — without imposing Source concepts on simpler Project or resource-sharing applications (REQ-SOURCE-APP-*, REQ-SOURCE-*) -### 2.3 Post-MVP capability integrations (NDO, Unyt, Flowsta) +### 2.3 Post-MVP capability integrations and application profiles The **current MVP** in this repository implements `ResourceSpecification`, `EconomicResource`, and `GovernanceRule` with governance-as-operator patterns as specified elsewhere in this document. **Normative requirements** for the generic **Nondominium Object (NDO)** — three-layer model, lifecycle vs operational state, capability slot surface, and typed integration with external operators — live in **[ndo_prima_materia.md](ndo_prima_materia.md)** (REQ-NDO-L0 through REQ-NDO-AGENT-08, REQ-NDO-CS-01 through REQ-NDO-CS-15, migration §10). -Optional, pay-as-you-grow integrations (communities may adopt one, both, or neither): +Optional, pay-as-you-grow integrations and application profiles (communities may adopt any subset): | Integration | Role | Normative detail | Design stub | |-------------|------|------------------|-------------| | **Lobby DNA** | Multi-network federation: entry point (Lobby DHT) + per-group coordination (Group DHT) + NDO-to-NDO hard links, Contributions, Smart Agreements; dual deployment (standalone + Moss applet) | REQ-LOBBY-*, REQ-GROUP-*, REQ-NDO-EXT-* | [lobby-dna.md](post-mvp/lobby-dna.md) / [lobby-architecture.md](../specifications/post-mvp/lobby-architecture.md) | | **Unyt** | Economic settlement (Smart Agreements, RAVE proofs, PPR↔RAVE provenance) | `ndo_prima_materia.md` §6.6, §11.5; REQ-NDO-CS-07–CS-11 | [unyt-integration.md](post-mvp/unyt-integration.md) | | **Flowsta** | Cross-app identity (Vault `IsSamePersonEntry`, `FlowstaIdentity` slot, DID, recovery); Tier 1 (Phase 1) vs Tier 2 (Phase 3) | `ndo_prima_materia.md` §6.5–6.7, §11.6; REQ-NDO-CS-12–CS-15; REQ-NDO-AGENT-07–08 | [flowsta-integration.md](post-mvp/flowsta-integration.md) | -| **Source-NDO** | `Source` as a third ontological primitive (neither Agent nor Resource): generative ecological systems (watersheds, rivers, forests, fisheries) and knowledge commons. Yields Resources, receives ecological effects, conditions future possibilities. Requires `vf:Source` ValueFlows extension, `SourceProfile` Layer 0 extension, `stewardedBy` stewardship model, and adaptive cybernetic governance loop. | REQ-SOURCE-ONT-*, REQ-SOURCE-GOV-*, REQ-SOURCE-DATA-*, REQ-SOURCE-EVENT-* | [source-ndo-requirements.md](post-mvp/source-ndo-requirements.md) / [source-ndo-paper.md](post-mvp/source-ndo-paper.md) | +| **Source-NDO application profile** | Optional third primitive for applications governing generative ecological or knowledge systems. Not activated for ordinary Project NDOs (e.g. open-hardware design) or mature-resource mutualisation (e.g. sharing a 3D printer) unless the application explicitly needs to govern a generative Source and its boundary effects. | REQ-SOURCE-APP-*, REQ-SOURCE-ONT-*, REQ-SOURCE-GOV-*, REQ-SOURCE-DATA-*, REQ-SOURCE-EVENT-*; REQ-USER-ST-*, REQ-UI-SOURCE-* (§4.6) | [source-ndo-requirements.md](post-mvp/source-ndo-requirements.md) / [source-ndo-paper.md](post-mvp/source-ndo-paper.md) | -**Knowledge-base context** (ontology, OVN alignment, gap analysis): [resources.md](../archives/resources.md), [agent.md](../archives/agent.md), [governance.md](../archives/governance.md). This PRD remains the anchor for MVP user stories and REQ-USER / REQ-RES / REQ-GOV IDs; NDO-wide REQ-NDO-* IDs are defined in `ndo_prima_materia.md` §9. +**Knowledge-base context** (ontology, OVN alignment, gap analysis): [resources.md](../archives/resources.md), [agent.md](../archives/agent.md), [governance.md](../archives/governance.md), [source-ndo-requirements.md](post-mvp/source-ndo-requirements.md). This PRD remains the anchor for MVP user stories and REQ-USER / REQ-RES / REQ-GOV IDs; NDO-wide REQ-NDO-* IDs are defined in `ndo_prima_materia.md` §9; Source-NDO REQ-SOURCE-* IDs are defined in `source-ndo-requirements.md` §8. ## 3. nondominium Resource Characteristics +The requirements below apply to **appropriable Resources** (`EconomicResource` instances under a `ResourceSpecification`). They do **not** apply to **Sources** (generative ecological or knowledge systems modeled as Source-NDOs post-MVP) — see §4.6 and REQ-SOURCE-ONT-02. In Ostrom's SES terms: a Source is the *resource system*; an `EconomicResource` is the *resource unit* extracted or held in custody from it. + nondominium Resources must exhibit the following characteristics: - **REQ-RES-01: Permissionless Access**: Anyone can access nondominium Resources under defined governance rules. *Post-MVP note*: "defined governance rules" must be extensible to include `AffiliationState`-based conditions (e.g. `min_affiliation: ActiveAffiliate`) in addition to role-based conditions; see `REQ-AGENT-03`, `REQ-AGENT-05`, and `REQ-GOV-09` annotation below. @@ -67,6 +72,7 @@ nondominium Resources must exhibit the following characteristics: - **REQ-RES-07: Shareable by Default**: Resources are designed for sharing from inception - **REQ-RES-08: Process-Enabled**: Resources can be used in structured Economic Processes (Use, Transport, Storage, Repair) - **REQ-RES-09: Lifecycle Managed**: Resources have managed lifecycles from creation through validation to end-of-life +- **REQ-RES-10: Source Boundary (post-MVP)**: Generative ecological or knowledge systems (watersheds, rivers, forests, fisheries, open knowledge commons) SHALL NOT be modeled as owned `EconomicResource` instances with a `primaryAccountable` custodian when their correct ontological category is **Source**. Such systems SHALL be registered as Source-NDOs (`NondominiumIdentity` + `SourceProfile`) with `property_regime` of `Nondominium` or `CommonPool` only. Extracted or appropriated units (water m³, fish landed, timber cut) remain `EconomicResource` instances linked to boundary events on the Source. See REQ-SOURCE-ONT-01, REQ-SOURCE-ONT-02, and §4.6. ## 4. User Roles & Stories @@ -107,7 +113,7 @@ A user who can signal intent to access Resources and participate in governance. **Role & Process Management** -- **REQ-USER-A-05**: As an Accountable Agent, I want to acquire specialized roles (Transport, Repair, Storage) through validation +- **REQ-USER-A-05**: As an Accountable Agent, I want to acquire specialized roles (Transport, Repair, Storage) through validation. *Conditional post-MVP note*: applications that enable the Source-NDO profile add **Steward** as a validated functional role for generative-system governance (§4.6, REQ-USER-ST-*); other applications do not expose it - **REQ-USER-A-06**: As an Accountable Agent, I want to initiate and complete Economic Processes according to my roles - **REQ-USER-A-07**: As an Accountable Agent, I want to chain multiple process actions (e.g., transport → repair → transport) in a single commitment @@ -153,7 +159,7 @@ The agent with physical possession (custodianship) of a material nondominium Res - **REQ-AGENT-04: Five-State Affiliation**: The system must model the OVN affiliation spectrum — UnaffiliatedStranger, CloseAffiliate, ActiveAffiliate, CoreAffiliate, InactiveAffiliate — as a *derived* (not stored) property computed algorithmically from PPR activity, recency, and contribution history. Binary "in/out" membership is insufficient for governance decisions. - **REQ-AGENT-05: Affiliation Record**: Formal network entry must be formalised as an `AffiliationRecord` entry: the agent cryptographically signs acknowledgement of the Terms of Participation (ToP), the Nondominium & Custodian agreement, and the Benefit Redistribution Algorithm. This record is the prerequisite for `ActiveAffiliate` status. -- **REQ-AGENT-06: Configurable Role Taxonomy**: The `RoleType` enum must become configurable at the network level. Communities must be able to define their own role taxonomies rather than relying on the six predefined types (`SimpleAgent`, `AccountableAgent`, `PrimaryAccountableAgent`, `Transport`, `Repair`, `Storage`). Predefined roles become defaults, not constraints. +- **REQ-AGENT-06: Configurable Role Taxonomy**: The `RoleType` enum must become configurable at the network level. Communities must be able to define their own role taxonomies rather than relying on the six predefined types (`SimpleAgent`, `AccountableAgent`, `PrimaryAccountableAgent`, `Transport`, `Repair`, `Storage`). Predefined roles become defaults, not constraints. *Post-MVP note*: Source-enabled applications add **`Steward`** as an application-profile role for generative-system governance (§4.6); applications without Sources SHALL NOT expose or require it. ### Composable Profile @@ -214,6 +220,86 @@ These requirements govern the Svelte 5 / SvelteKit frontend implemented in the ` - **REQ-UI-NDO-04: Transition History**: NDO identity panels must show a collapsible transition history panel listing `from_stage`, `to_stage`, `agent`, `timestamp`, and `event_hash` (with copy-to-clipboard) for each recorded transition. - **REQ-UI-NDO-05: Fork Button**: An informational "Fork this NDO" button must be accessible to all authenticated users. The fork modal must explain the fork friction concept (negotiation, consensus, post-MVP Unyt stake) and provide a copy-initiator-pubkey CTA. Actual fork submission is post-MVP. +## 4.6 Source Ontology Requirements (Post-MVP) + +> **Status**: Optional post-MVP application profile. Normative REQ-SOURCE-* IDs and full data-model specification live in [source-ndo-requirements.md](post-mvp/source-ndo-requirements.md). Academic grounding: [source-ndo-paper.md](post-mvp/source-ndo-paper.md). Implementation phasing: [implementation_plan.md](../implementation_plan.md) §12.7. Source-NDO does not break existing REQ-NDO-* invariants (Layer 0 permanence, PPR privacy model) and is not part of the minimum UI or ontology for every NDO application. + +### Applicability and progressive activation + +Source follows **dynamic complexity matching**: the application SHALL expose only the primitives required by its actual coordination problem. Agent + Resource remain the baseline. Source is activated only when agents must govern a generative system's condition, boundary flows, regeneration, or assimilation capacity. + +**Source is normally relevant when:** +- the object of governance is a resource system rather than an appropriable unit (e.g. watershed vs water in a tank; fishery vs landed fish); +- extraction, loading, regeneration, or coupled Source condition must be visible on-ledger; +- adaptive stewardship rules must respond to accumulated condition signals. + +**Source is normally not relevant when:** +- a Project-type NDO coordinates the design of an open-source hardware device; Agents contribute work and the design/artifacts are Resources; +- an NDO represents a mature, in-use Resource being mutualised, such as a 3D printer shared within or between Groups; Agents, custody, access, maintenance, and Resource events are sufficient; +- no generative system or Source boundary is itself being governed. Provenance from nature alone does not require Source activation. + +- **REQ-SOURCE-APP-01: Optional Application Profile**: Source support SHALL be an opt-in application/profile capability, not a mandatory primitive in every NDO creation flow or detail view. +- **REQ-SOURCE-APP-02: Complexity-Matched Activation**: Applications SHALL activate Source features only when their domain requires governance of a generative system or its boundary effects. Ordinary Project and resource-mutualisation flows SHALL remain complete using Agent and Resource primitives alone. +- **REQ-SOURCE-APP-03: No Universal UI Burden**: Applications that do not enable the Source profile SHALL NOT display Source type selectors, regime-state fields, stewardship workflows, Source coupling graphs, or Source-specific navigation. +- **REQ-SOURCE-APP-04: Progressive Enablement**: Enabling Source support SHALL add Source-specific data, governance, and UI modules without changing existing Agent/Resource semantics or requiring existing NDOs to migrate into Source-NDOs. + +### Ontological position + +ValueFlows and REA model **Agent** (acts, commits, bears responsibility) and **Resource** (appropriable output). A river, watershed, forest, or fishery fits neither honestly: as `EconomicResource` it implies ownership; as `Agent` it imports false intention; omitted entirely, extraction appears as resource-from-nowhere (`raise`) and depletion vanishes from the ledger. + +**`Source`** is the third flow endpoint: a generative, non-ownable, partially unknowable system that yields Resources, receives ecological effects, conditions other Sources, and accumulates boundary-event history for adaptive stewardship. Source-NDOs use the same three-layer NDO model; Layer 0 carries a linked **`SourceProfile`**; stewardship uses **`stewardedBy`** (obligations), not `primaryAccountable` (ownership). + +| Ostrom SES concept | Nondominium mapping | +|---|---| +| Resource system | **Source** (`SourceProfile` on Layer 0) | +| Resource unit | **`EconomicResource`** | +| Governance system | `GovernanceRule` + adaptive loop (§6.6) | +| Users / actors | **Agents** (+ **`Steward`** functional role) | + +- **REQ-SOURCE-ONT-01**: The system SHALL recognise `Source` as a distinct ontological category for flow endpoints in economic events, separable from both `Agent` and `EconomicResource` (`vf:Source` ValueFlows extension). +- **REQ-SOURCE-ONT-02**: Source-NDOs SHALL NOT require a `primaryAccountable` agent. `property_regime` SHALL be `Nondominium` or `CommonPool` only. Governance SHALL reject any rule that assigns Source ownership or alienation. +- **REQ-SOURCE-ONT-03**: The system SHALL support Source-to-Source links (`yields`, `conditions`, `providedBy`) for hierarchies and ecological coupling (e.g. watershed → river; forest conditions river flow). +- **REQ-SOURCE-ONT-04**: Source-NDOs SHALL be `NondominiumIdentity` entries with a linked `SourceProfile`, using the permanent Layer 0 hash as the boundary-event ledger anchor. + +### Data model + +- **REQ-SOURCE-DATA-01**: `SourceProfile` SHALL record ecological condition state (`current_stock`, `flux_rate`, `assimilation_capacity`, `regime_state`, `resilience`, `tipping_threshold`), complexity-economics indicators (`adaptive_capacity`, `generative_capacity`, `dependency_index`), classification (`source_type`, `complex_interior`), and `stewarded_by`. Full field spec: `source-ndo-requirements.md` §4.1. +- **REQ-SOURCE-DATA-02**: `SourceRegimeState` SHALL progress through `Pristine → Stable → Stressed → Degraded → Critical → Transformed`, with governance-validated transitions (not unilateral writes). +- **REQ-SOURCE-DATA-03**: Layer 1 `SourceSpecification` SHOULD support a multidimensional ecological value vector (Sustenance, Regeneration, Resilience, Adaptive Capacity, Generative Capacity, Commons Value, Learning Value). + +**Black-box principle:** Ecological Source interiors are not modeled. Governance operates on observable boundary signals (withdrawals, pollutant loads, monitoring data, community observation) and adapts rules from the accumulated ledger — consistent with complexity-science treatment of SES as partially unknowable (`source-ndo-requirements.md` §2.4, §5.1). + +### Steward user stories + +The **`Steward`** role is a functional stewardship role (obligations without alienation rights), distinct from `PrimaryAccountableAgent` custody of material Resources. + +**Source registration and monitoring** + +- **REQ-USER-ST-01**: As a Steward, I want to register a Source-NDO (watershed, river, fishery, knowledge commons) with initial condition indicators and named co-stewards, without assigning ownership +- **REQ-USER-ST-02**: As a Steward, I want to submit monitoring data and qualitative condition observations that update the Source's regime state through governance-validated assessment +- **REQ-USER-ST-03**: As a Steward, I want to link sub-Sources and coupling relations (watershed yields river; forest conditions river) so ecological structure is legible on the DHT + +**Boundary events and access** + +- **REQ-USER-ST-04**: As an Accountable Agent, I want to record extraction from a Source (provider: Source, receiver: Agent) so depletion is visible against `current_stock` or period quota — not as a phantom `raise` +- **REQ-USER-ST-05**: As an Accountable Agent, I want to record pollutant loading into a Source (receiver: Source) so assimilation capacity debits are visible on-ledger +- **REQ-USER-ST-06**: As a Steward, I want access affordance rules (quotas, seasonal limits, discharge caps) to adapt when regime state or monitoring indicates stress, through a defined governance process — not only static one-shot rule evaluation + +**Governance adaptation** + +- **REQ-USER-ST-07**: As a Steward, I want to propose `SourceRegimeState` transitions with evidence and multi-validator approval when ecological interpretation changes +- **REQ-USER-ST-08**: As a Steward, I want precautionary blocking when a proposed boundary event would push the Source past its `tipping_threshold` +- **REQ-USER-ST-09**: As a Steward, I want to participate in stewardship succession (transfer of steward obligations) through governance-validated events, without privatising the Source + +### Source UI requirements (conditional post-MVP profile) + +The following requirements apply **only when the host application enables the Source-NDO profile**. They SHALL NOT expand the default Project or resource-mutualisation UI. + +- **REQ-UI-SOURCE-01**: A Source-enabled NDO creation flow SHALL offer a distinct Source-NDO variant with `property_regime` restricted to `Nondominium` / `CommonPool`, `SourceType` selection, steward assignment, and optional initial condition fields. The generic NDO form SHALL remain unchanged when Source support is disabled +- **REQ-UI-SOURCE-02**: Source-enabled detail views SHALL display regime state, condition indicators, steward list, and boundary-event history linked to the Layer 0 hash; ordinary Resource and Project detail views SHALL omit these panels +- **REQ-UI-SOURCE-03**: A Source-enabled application SHALL visualise Source hierarchies and coupling links (watershed → river → resources) when Layer 1/Composition views mature +- **REQ-UI-SOURCE-04**: Source-enabled applications SHALL provide stewards a dashboard for monitoring obligations, pending regime transitions, and access-affordance rule proposals + ## 5. Economic Process Requirements ### 5.1 Core Process Types @@ -231,6 +317,15 @@ These requirements govern the Svelte 5 / SvelteKit frontend implemented in the ` - **REQ-PROC-08: Process Chaining**: Agents with multiple roles can chain process actions within a single commitment - **REQ-PROC-09: Process History**: Complete audit trail of all processes affecting each Resource +### 5.3 Source boundary events (Conditional Post-MVP Profile) + +> **Status**: Applies only to Source-enabled applications. Requires `vf:Source` and the Source-NDO data model (§4.6). Boundary events on Sources are economic events where the Source is provider or receiver — distinct from, and unnecessary for, ordinary custody and use processes on `EconomicResource` instances. + +- **REQ-PROC-10: Source Extraction Recording**: Extraction of resource units from a Source (water abstraction, fish harvest, timber cut) SHALL be recorded as boundary `EconomicEvent` entries with the Source as provider and an Agent as receiver, decrementing `SourceProfile.current_stock` or period quota — not as unanchored `raise` events (REQ-SOURCE-EVENT-01, REQ-SOURCE-EVENT-02) +- **REQ-PROC-11: Source Loading Recording**: Discharge, pollutant loading, or waste deposition into a Source SHALL be recorded with the Source as receiver, decrementing `assimilation_capacity` where applicable (REQ-SOURCE-EVENT-01, REQ-SOURCE-EVENT-02) +- **REQ-PROC-12: Source Regeneration Recording**: Restoration, remediation, or regeneration actions on a Source (reforestation, riparian repair) SHALL be recordable as governance-validated events that may increment stock, flux, assimilation capacity, or resilience indicators (REQ-SOURCE-EVENT-03) +- **REQ-PROC-13: Non-Consumptive Source Use**: Non-consumptive use of a Source (e.g. hydro flow alteration affecting regime without volume extraction) SHALL be recordable as boundary events affecting `SourceRegimeState` or flux characteristics without implying Resource custody transfer + ## 6. Governance & Validation Requirements ### 6.1 Resource Lifecycle Management @@ -248,8 +343,8 @@ These requirements govern the Svelte 5 / SvelteKit frontend implemented in the ` ### 6.3 Governance Rules -- **REQ-GOV-08: Embedded Rules**: ResourceSpecifications must contain embedded governance rules for access and process management -- **REQ-GOV-09: Rule Enforcement**: Governance rules must be enforced programmatically across all interactions. *Post-MVP note*: the governance evaluation engine (`evaluate_transition`) must be extended to support `AffiliationState`-based rule conditions in addition to the current role-membership check. This requires a cross-zome query from `zome_governance` to `zome_person` to derive the requesting agent's `AffiliationState` before evaluating `GovernanceRule.rule_data["min_affiliation"]`. See `REQ-AGENT-03`, `REQ-AGENT-05`, `implementation_plan.md §3 [G2+Resource]`, and `governance-operator-architecture.md §2.1 TODO G2`. +- **REQ-GOV-08: Embedded Rules**: ResourceSpecifications must contain embedded governance rules for access and process management. *Post-MVP note*: Source-NDOs use Layer 1 **`SourceSpecification`** for boundary definitions, monitoring framework, and access-affordance rule templates; adaptive revision is governed by §6.6 +- **REQ-GOV-09: Rule Enforcement**: Governance rules must be enforced programmatically across all interactions. *Post-MVP note*: the governance evaluation engine (`evaluate_transition`) must be extended to support `AffiliationState`-based rule conditions in addition to the current role-membership check. This requires a cross-zome query from `zome_governance` to `zome_person` to derive the requesting agent's `AffiliationState` before evaluating `GovernanceRule.rule_data["min_affiliation"]`. See `REQ-AGENT-03`, `REQ-AGENT-05`, `implementation_plan.md §3 [G2+Resource]`, and `governance-operator-architecture.md §2.1 TODO G2`. *Source-NDO note*: Source governance extends evaluation with an **adaptive loop** — boundary events accumulate on the Source Layer 0 hash, ecological interpretation feeds rule revision, and revised access affordances condition future boundary events (§6.6). - **REQ-GOV-10: Rule Transparency**: All governance rules must be publicly visible and machine-readable ### 6.4 End-of-Life Management @@ -288,6 +383,28 @@ These requirements govern the Svelte 5 / SvelteKit frontend implemented in the ` pseudonymous agents are blocked from governance roles requiring legal accountability (refs G10, `governance.md §5.3`) +### 6.6 Source governance and adaptive stewardship (Conditional Post-MVP Profile) + +> **Status**: Applies only to Source-enabled applications. Full REQ-SOURCE-GOV-* set in [source-ndo-requirements.md](post-mvp/source-ndo-requirements.md) §5.3. Extends governance-as-operator with a **cybernetic** loop for complex ecological systems — rules adapt as the Source event ledger grows, without modeling ecological interiors (black-box principle). Applications that coordinate Projects or mutualise mature Resources continue to use ordinary governance-as-operator without this loop. + +**Adaptive governance loop:** + +```text +boundary events → ledger on Source L0 hash → ecological interpretation + → governance rule revision → access affordances → conditioned future events +``` + +- **REQ-SOURCE-GOV-01**: Source-NDO governance MUST support adaptive rule revision with maintained rule version history; rules SHALL be updatable through a defined governance process, not only by the initiator +- **REQ-SOURCE-GOV-02**: Source-NDOs MUST support access affordance rules as quantitative constraints on boundary events (extraction quotas, discharge caps, seasonal limits, minimum restoration per extraction) +- **REQ-SOURCE-GOV-03**: Governance evaluation for Source boundary events MUST check `SourceRegimeState` and MAY block or require multi-validator approval when an event would approach or exceed `tipping_threshold` +- **REQ-SOURCE-GOV-04**: Source-NDOs SHOULD support monitoring obligations as a `GovernanceRule` class: continued access may require condition-data submission that updates `SourceProfile` indicators +- **REQ-SOURCE-GOV-05**: `SourceRegimeState` transitions MUST be governance-validated with evidence and multi-validator approval +- **REQ-SOURCE-GOV-06**: All Source boundary events MUST be recorded as `EconomicEvent` entries linked to the Source's Layer 0 hash, forming an auditable ledger +- **REQ-SOURCE-GOV-07**: Source-NDOs MUST accept qualitative and community-validated condition signals (narrative observation, indigenous knowledge assessments) as legitimate governance inputs alongside quantitative monitoring +- **REQ-SOURCE-GOV-08**: Sensitive ecological data attached to Source records SHALL use Holochain private entries with capability-grant access control, following the `PrivatePersonData` model + +**Stewardship vs custody:** Sources have no `EconomicResource.custodian`. Responsibility is expressed through `stewardedBy` links and the `Steward` role — obligations to monitor, interpret, and implement governance decisions, without alienation or privatisation rights (REQ-SOURCE-ONT-02; `source-ndo-requirements.md` §5.4). + ## 7. Private Participation Receipt (PPR) Requirements ### 7.1 Receipt Generation @@ -319,6 +436,23 @@ These requirements govern the Svelte 5 / SvelteKit frontend implemented in the ` - **REQ-PPR-14: ZKP-Compatible Reputation Sharing**: The reputation summary derived from PPRs must be ZKP-compatible, allowing agents to produce proofs of the form "I have at least N claims of type T" without revealing the counterparties, timestamps, or raw scores. This is a prerequisite for privacy-preserving meritocracy — governance access based on contribution without requiring surveillance. - **REQ-PPR-15: Cross-Network Reputation Export**: The `ReputationSummary` must be exportable as a `PortableCredential` (see `REQ-AGENT-12`), signed by a Primary Accountable Agent and countersigned by the claim owner, verifiable by receiving networks. Without portability, contribution history cannot flow across organisational boundaries, blocking growth of the P2P ecosystem. +### 7.5 Source stewardship receipts (Conditional Post-MVP Profile) + +> **Status**: Applies only to Source-enabled applications. Uses the existing 16-category PPR taxonomy; Source interactions do not introduce a global reputation aggregator. Stewardship participation remains user-sovereign private entries. + +Source-NDO stewardship emphasises these PPR categories (`source-ndo-requirements.md` §7): + +| Category | Source-NDO use | +|---|---| +| `ResourceCreation` | Registration of a new Source-NDO and initial condition assessment | +| `ValidationActivity` | Monitoring submission, condition assessment, governance interpretation | +| `RuleCompliance` | Compliance with extraction quotas, discharge limits, monitoring obligations | +| `MaintenanceCommitmentAccepted` / `MaintenanceFulfillmentCompleted` | Restoration commitments (reforestation, remediation, riparian repair) | +| `DisputeResolutionParticipation` | Disputes over condition assessment or access affordances | +| `GoodFaithTransfer` | Stewardship succession — transfer of steward obligations | + +- **REQ-PPR-16: Stewardship PPR Eligibility**: Stewardship participation on Source-NDOs (monitoring, restoration, governance interpretation, rule compliance) SHALL generate bilateral PPRs using the existing private-entry model, enabling stewards to accumulate governance standing through contribution to Source health without exposing individual interaction history by default + ## 8. Security & Access Control ### 8.1 Capability-Based Security @@ -331,7 +465,7 @@ These requirements govern the Svelte 5 / SvelteKit frontend implemented in the ` - **REQ-SEC-04: Private Identity**: Personal identification information stored as Holochain private entries - **REQ-SEC-05: Private Receipts**: Participation receipts stored privately while enabling reputation derivation -- **REQ-SEC-06: Selective Disclosure**: Agents control what private information to share and with whom +- **REQ-SEC-06: Selective Disclosure**: Agents control what private information to share and with whom. *Post-MVP note*: sensitive ecological data on Source-NDOs (endangered species locations, sacred sites) follows the same capability-grant model as `PrivatePersonData` (REQ-SOURCE-GOV-08) ### 8.3 Network Security @@ -343,21 +477,21 @@ These requirements govern the Svelte 5 / SvelteKit frontend implemented in the ` ### 9.1 Zome Structure -The hApp must be structured with three zomes: +The hApp must be structured with three zomes. Source support, where enabled, SHALL be added as profile-specific modules within these zomes rather than imposed on every application: -- **`zome_person`**: Agent identity, roles, reputation, and private data management -- **`zome_resource`**: Resource specifications, economic resources, and process management (pure data model) -- **`zome_governance`**: Validation, commitments, claims, and PPR issuance +- **`zome_person`**: Agent identity, roles, reputation, and private data management. *Source-enabled profile only*: `Steward` functional role (§4.6) +- **`zome_resource`**: Resource specifications, economic resources, and process management (pure data model). *Source-enabled profile only*: `SourceProfile`, Source coupling links, and Source-NDO creation extending Layer 0 (§4.6) +- **`zome_governance`**: Validation, commitments, claims, and PPR issuance. *Source-enabled profile only*: Source-as-provider/receiver on `EconomicEvent` and adaptive Source governance evaluation (§6.6) ### 9.2 ValueFlows Compliance -- **REQ-ARCH-01: REA Model**: Implement Resources, Events, Agents pattern with Economic Processes -- **REQ-ARCH-02: Standard Actions**: Support all relevant ValueFlows actions with nondominium-specific extensions -- **REQ-ARCH-03: Multi-Layer Ontology**: Support Knowledge, Plan, and Observation levels +- **REQ-ARCH-01: REA Model**: Implement the Agent–Resource–Event pattern with Economic Processes. *Conditional post-MVP extension*: Source-enabled applications recognise **Source** as a third flow endpoint (`vf:Source`) so boundary events on generative systems are first-class economic records; other applications remain complete with Agent and Resource (REQ-SOURCE-APP-02, REQ-SOURCE-ONT-01) +- **REQ-ARCH-02: Standard Actions**: Support all relevant ValueFlows actions with nondominium-specific extensions. *Source-enabled profile only*: boundary events use extraction, loading, non-consumptive use, and regeneration (`raise` on a Source) with Sources as provider or receiver — see REQ-SOURCE-EVENT-* and §5.3 +- **REQ-ARCH-03: Multi-Layer Ontology**: Support Knowledge, Plan, and Observation levels. *Source-enabled profile only*: Layer 0 = `NondominiumIdentity` + `SourceProfile`; Layer 1 = `SourceSpecification`; Layer 2 = boundary events, commitments, claims, PPRs (`source-ndo-requirements.md` §6) ### 9.3 Modular Governance Architecture -**REQ-ARCH-07: Modular Governance**: The resource zome operates as a pure data model, while the governance zome operates as a state transition operator. This separation enables independent evolution of data structures and governance rules. +**REQ-ARCH-07: Modular Governance**: The resource zome operates as a pure data model, while the governance zome operates as a state transition operator. This separation enables independent evolution of data structures and governance rules. *Conditional post-MVP note*: the Source profile extends the operator with an adaptive ecological loop; the base operator SHALL NOT depend on Source types or require Source configuration. **Business Benefits**: - **Swappable Governance**: Governance rules can be updated without modifying resource data structures @@ -380,7 +514,7 @@ The hApp must be structured with three zomes: - **Event Generation**: All state changes must generate corresponding economic events - **Audit Trail**: Complete history of governance decisions and state changes -**REQ-ARCH-10: Event-Driven State Changes**: All resource state changes must generate corresponding economic events to maintain complete ValueFlows compliance and audit trails. +**REQ-ARCH-10: Event-Driven State Changes**: All resource state changes must generate corresponding economic events to maintain complete ValueFlows compliance and audit trails. *Post-MVP note*: Source boundary events (extraction, loading, regeneration) and governance-validated `SourceProfile` indicator updates are economic events anchored to the Source Layer 0 hash (REQ-SOURCE-GOV-06, REQ-ARCH-12). **Event Requirements**: - **Complete History**: Every state transition must be recorded as an economic event @@ -394,6 +528,14 @@ The hApp must be structured with three zomes: - **REQ-ARCH-05: Link Management**: Proper linking between related entries across zomes - **REQ-ARCH-06: State Management**: Resource and process state tracking with proper transitions +### 9.5 Source flow endpoints (Conditional Post-MVP Profile) + +These requirements apply only when Source support is enabled. An application satisfying Agent/Resource use cases SHALL NOT need to implement or surface Source endpoints. + +- **REQ-ARCH-11: vf:Source Extension**: A Source-enabled economic event model SHALL support `vf:Source` as a typed flow endpoint role, enabling `EconomicEvent` entries where a Source is provider (extraction, non-consumptive use) or receiver (loading, pollution) without attributing agency to the Source or ownership via `primaryAccountable` (REQ-SOURCE-ONT-01, REQ-SOURCE-EVENT-01) +- **REQ-ARCH-12: Source Event Ledger**: Boundary events on a Source SHALL anchor to the Source's permanent Layer 0 `NondominiumIdentity` hash, enabling queryable history of extraction, loading, restoration, and regime-relevant use independent of `EconomicResource` custody chains (REQ-SOURCE-GOV-06) +- **REQ-ARCH-13: Source Condition Updates**: Updates to `SourceProfile` indicators (`current_stock`, `assimilation_capacity`, `regime_state`, etc.) from boundary events SHALL be governance-validated state transitions, not direct writes by extracting or discharging agents (REQ-SOURCE-EVENT-02) + ## 10. Future Enhancements ### Phase 2 Requirements @@ -409,6 +551,7 @@ The hApp must be structured with three zomes: - Advanced reputation algorithms and trust networks - Scalable validation schemes for large networks - Economic incentive mechanisms and value accounting +- **Source-NDO (optional application profile)**: For applications governing generative systems only — `SourceProfile`, `vf:Source` boundary events, adaptive stewardship, and cross-DNA source hierarchies (§4.6, §6.6; `implementation_plan.md` §12.7) ## 11. Future Development: Architecture Variants for P2P and Organizational Contexts @@ -527,7 +670,7 @@ While the core ValueFlows logic and resource model remain consistent, the govern ### 11.8 Architecture Modularity Requirements - **REQ-FUT-ARCH-01**: Design modular architecture supporting both P2P and organizational contexts -- **REQ-FUT-ARCH-02**: Core ValueFlows and resource model must remain context-agnostic +- **REQ-FUT-ARCH-02**: Core ValueFlows and resource model must remain context-agnostic. *Post-MVP note*: Source is an optional extension profile that must not burden organizational bridges or applications that need only Agent/Resource semantics; when enabled, extracted units remain `EconomicResource` and generative systems remain Source-NDOs - **REQ-FUT-ARCH-03**: Governance and identity layers must support pluggable implementations - **REQ-FUT-ARCH-04**: Support seamless interoperability between P2P agents and organizational agents - **REQ-FUT-ARCH-05**: Enable organizations to act as agents in the P2P network with equal standing @@ -575,3 +718,4 @@ The nondominium system is successful when: 4. Economic Processes support real-world sharing scenarios 5. System scales while maintaining decentralized principles 6. Privacy is preserved while enabling accountability +7. **(Conditional post-MVP)** Applications whose domain includes generative ecological or knowledge commons can enable Source-NDO so boundary events are visible and stewardship adapts, while Project and mature-resource mutualisation applications remain simple and complete with Agent and Resource primitives diff --git a/documentation/requirements/resources.md b/documentation/requirements/resources.md index 5a70289..5b7649e 100644 --- a/documentation/requirements/resources.md +++ b/documentation/requirements/resources.md @@ -159,7 +159,7 @@ pub struct EconomicResource { // to support Collective, Project, Network, and Bot agents as // Primary Accountable Agents. Currently assumes individual agent. pub current_location: Option, - pub state: ResourceState, + - operational_state: OperationalState, } ``` This is the **observation layer**: a specific instance of a resource at a point in time, held by a specific custodian. @@ -174,18 +174,13 @@ pub struct GovernanceRule { ``` Economic rules governing access and use. Currently entirely untyped — `rule_data` is a free-form JSON string with no schema enforcement. - ToDo: explore how to make governance rules machine readable and executable, typed. -**`ResourceState`** (enum on `EconomicResource`) — *still conflated; `OperationalState` split pending (`REQ-NDO-OS-06`)* +**`OperationalState`** (enum on `EconomicResource`) — ✅ **implemented** (`REQ-NDO-OS-01`) ``` -PendingValidation | Active | Maintenance | Retired | Reserved +PendingValidation | Available | Reserved | InTransit | InStorage | InMaintenance | InUse ``` -`LifecycleStage` is **implemented** on `NondominiumIdentity` (see above). The legacy `ResourceState` on `EconomicResource` still conflates maturity and operational condition. The code contains an explicit `TODO` to split into: - -- **`LifecycleStage`** — on `NondominiumIdentity` (✅ implemented) -- **`OperationalState`** — on `EconomicResource` (🔄 not implemented): `PendingValidation | Available | Reserved | InTransit | InStorage | InMaintenance | InUse` - -`Maintenance` and `Reserved` in the current enum are operational conditions, not lifecycle milestones. A resource being repaired is still `LifecycleStage::Active` — it would have `OperationalState::InMaintenance` once the split lands. +`LifecycleStage` is **implemented** on `NondominiumIdentity` (see above). Operational condition cycles on the instance independently of lifecycle maturity — e.g. an `Active`-stage NDO can have an `InMaintenance` economic resource instance. ### 2.2 Link Graph @@ -195,7 +190,7 @@ The link types model resource discovery and navigation: - Anchor links for global discovery (`AllResourceSpecifications`, `AllEconomicResources`, `AllGovernanceRules`) - Hierarchical links (`SpecificationToResource`, `SpecificationToGovernanceRule`) - Agent-centric links (`CustodianToResource`, `AgentToOwnedSpecs`, `AgentToManagedResources`) -- Faceted search links (`SpecsByCategory`, `ResourcesByLocation`, `ResourcesByState`, `RulesByType`) +- Faceted search links (`SpecsByCategory`, `ResourcesByLocation`, `ResourcesByOperationalState`, `RulesByType`) - Governance links (`ResourceToValidation`) - Update chain links (for Holochain's append-only update pattern) @@ -224,7 +219,7 @@ The link types model resource discovery and navigation: | Gap | Impact | Status / planned fix | |---|---|---| -| `ResourceState` conflates lifecycle and operational dimensions on `EconomicResource` | Cannot model in-transit, in-storage, or in-maintenance instances independently of Layer 0 lifecycle | 🔄 **`OperationalState` split pending** (`REQ-NDO-OS-06`); `LifecycleStage` on Layer 0 is ✅ done | +| ~~`ResourceState` conflates lifecycle and operational dimensions~~ | ~~Cannot model in-transit, in-storage, or in-maintenance instances independently of Layer 0 lifecycle~~ | ✅ **`OperationalState` on `EconomicResource`** (`REQ-NDO-OS-01`); governance-operator transitions deferred (`REQ-NDO-OS-02`–`05`) | | ~~No property regime field~~ | ~~Cannot distinguish nondominium from commons from individual stewardship~~ | ✅ **`PropertyRegime` on `NondominiumIdentity`** (see §2.6 for 6-vs-4 variant reconciliation) | | ~~No resource nature field~~ | ~~Cannot distinguish digital from physical from hybrid~~ | ✅ **`ResourceNature` on `NondominiumIdentity`** (5 variants in code; see §2.6) | | `GovernanceRule.rule_data` is untyped JSON string | No schema enforcement, no tooling support, no peer validation of rule semantics | 🔄 `GovernanceRuleType` enum with typed schemas (`ndo_prima_materia.md` + `unyt-integration.md`) | @@ -354,13 +349,7 @@ Hibernating → Deprecated → EndOfLife Hibernating records `hibernation_origin` and resumes to that stage. Deprecated requires `successor_ndo_hash` (REQ-NDO-LC-06). EndOfLife is terminal. -**`OperationalState`** — 🔄 **Not implemented** on `EconomicResource`. The legacy 5-state `ResourceState` enum still conflates both dimensions (`REQ-NDO-OS-06`): - -``` -PendingValidation | Available | Reserved | InTransit | InStorage | InMaintenance | InUse -``` - -`Maintenance` and `Reserved` in the current `ResourceState` enum are operational conditions, not lifecycle milestones. Transport, storage, and maintenance are *processes* that can apply to a resource at *any* lifecycle stage (a `Prototype` can be `InTransit` between labs; an `Active` resource can be `InMaintenance`). +**`OperationalState`** — ✅ **Implemented** on `EconomicResource` (7 states; `update_operational_state`, `get_resources_by_operational_state`). Governance-zome transition enforcement (`REQ-NDO-OS-02`–`03`) remains deferred. Each lifecycle transition **should** be governance-validated (the governance zome as state transition operator), generate an economic event, and create a lifecycle history audit trail (REQ-NDO-LC-02/03). Today: integrity zome validates transitions; automatic EconomicEvent generation and governance-as-operator evaluation are deferred. @@ -695,7 +684,7 @@ For the generic NDO, the implication is: **do not model intangible resources as | OVN concept | NDO partial coverage | Gap | |---|---|---| | Resource nature (physical/digital/media) | `ResourceNature` enum on Layer 0 (`Physical, Digital, Service, Hybrid, Information`) | Missing `Mental` analog (represented by Ideation-stage NDOs); media channel vs. media item distinction absent; forward-map `Space`/`Method`/`Currency` (§6.2) not in code | -| Operational vs lifecycle state | `LifecycleStage` on Layer 0 ✅; legacy `ResourceState` on `EconomicResource` | `OperationalState` split not implemented (`REQ-NDO-OS-06`) | +| Operational vs lifecycle state | `LifecycleStage` on Layer 0 ✅; `OperationalState` on `EconomicResource` ✅ | Governance-operator operational transitions (`REQ-NDO-OS-02`–`03`) deferred | | Governance of access (role-based) | Role-based `enforced_by` in GovernanceRule | Rule types are untyped strings; no first-class accessibility classification | | Material/Immaterial behavior | Physical vs. Digital/Information/Service nature | No formal rivalrous/non-rivalrous property | | Method as resource | `Digital` or `Information` nature covers some cases | No dedicated `Method` variant or template/recipe entry type | diff --git a/documentation/specifications/VfAction_Usage.md b/documentation/specifications/VfAction_Usage.md index f14ef8a..61dbdea 100644 --- a/documentation/specifications/VfAction_Usage.md +++ b/documentation/specifications/VfAction_Usage.md @@ -221,14 +221,12 @@ pub fn transport_resource_with_governance( ```rust // Repair process with state transition validation -// TODO: update new_operational_state parameter type from ResourceState to OperationalState -// once the ResourceState split is implemented (see ndo_prima_materia.md Section 5, REQ-NDO-OS-01). -// The repair process sets OperationalState::InMaintenance on the EconomicResource instance, -// while LifecycleStage on NondominiumIdentity remains unchanged. +// Repair sets OperationalState::InMaintenance on the EconomicResource instance; +// LifecycleStage on NondominiumIdentity remains unchanged (REQ-NDO-OS-01). pub fn repair_resource_with_governance( resource_hash: ActionHash, repair_details: String, - new_operational_state: Option, // TODO: → Option + new_operational_state: Option, ) -> ExternResult { let resource = get_economic_resource(resource_hash)?; diff --git a/documentation/specifications/governance/cross-zome-api.md b/documentation/specifications/governance/cross-zome-api.md index 21fd9a0..4974691 100644 --- a/documentation/specifications/governance/cross-zome-api.md +++ b/documentation/specifications/governance/cross-zome-api.md @@ -155,22 +155,24 @@ pub fn get_resources_by_specification( **Returns:** - `Vec` - Resources conforming to the specification -#### get_resources_by_state +#### get_resources_by_operational_state -Retrieves resources in a specific state. +Retrieves resources in a specific operational state. ```rust #[hdk_extern] -pub fn get_resources_by_state( - state: ResourceState, -) -> ExternResult> +pub fn get_resources_by_operational_state( + state: OperationalState, +) -> ExternResult> ``` **Parameters:** -- `state: ResourceState` - State to filter by +- `state: OperationalState` - Operational state to filter by **Returns:** -- `Vec` - Resources in the specified state +- `Vec` - Economic resource records in the specified operational state + +> Lifecycle maturity queries use `get_ndos_by_lifecycle_stage` on Layer 0 (`NdoByLifecycleStage`), not economic-resource links. ## 2. Governance Zome API diff --git a/documentation/specifications/governance/governance-operator-architecture.md b/documentation/specifications/governance/governance-operator-architecture.md index 7f4e6b7..e1adfff 100644 --- a/documentation/specifications/governance/governance-operator-architecture.md +++ b/documentation/specifications/governance/governance-operator-architecture.md @@ -226,7 +226,7 @@ impl ResourceManager { // 3. Apply state change if approved if governance_result.success { if let Some(new_state) = governance_result.new_resource_state { - self.update_resource_state(new_state)?; + self.update_operational_state(new_state)?; } if let Some(event) = governance_result.economic_event { @@ -301,7 +301,7 @@ pub fn request_resource_transition( // 3. Handle result and update local state if result.success { - update_resource_state(result.new_resource_state)?; + update_operational_state(result.new_resource_state)?; create_economic_event(result.economic_event)?; } diff --git a/documentation/specifications/governance/governance-operator-implementation-guide.md b/documentation/specifications/governance/governance-operator-implementation-guide.md index ac3c9c4..8a12677 100644 --- a/documentation/specifications/governance/governance-operator-implementation-guide.md +++ b/documentation/specifications/governance/governance-operator-implementation-guide.md @@ -103,7 +103,7 @@ pub fn request_resource_transition( true => { // 3a. Apply approved state changes if let Some(new_state) = governance_result.new_resource_state.clone() { - update_resource_state(new_state)?; + update_operational_state(new_state)?; } // 3b. Record economic event @@ -157,18 +157,19 @@ fn get_action_hash(resource: &EconomicResource) -> ExternResult { todo!("Implement action hash retrieval") } -// Validate that action is compatible with current resource state +// Validate that action is compatible with current operational state +// (LifecycleStage on NondominiumIdentity is validated separately — REQ-NDO-OS-02 deferred) fn validate_action_state_compatibility( action: &VfAction, - current_state: &ResourceState, + current_operational_state: &OperationalState, ) -> ExternResult<()> { - match (current_state, action) { - (ResourceState::Retired, _) => { + match (current_operational_state, action) { + (OperationalState::PendingValidation, VfAction::Use) => { return Err(ResourceError::InvalidInput( - "Cannot perform actions on retired resource".to_string() + "Cannot use resource pending validation".to_string() ).into()); } - (ResourceState::Reserved, VfAction::Use) => { + (OperationalState::Reserved, VfAction::Use) => { return Err(ResourceError::InvalidInput( "Cannot use reserved resource".to_string() ).into()); @@ -1023,19 +1024,19 @@ mod governance_tests { created_by: AgentPubKey::random(), created_at: sys_time().unwrap(), current_location: Some("Workshop".to_string()), - state: ResourceState::Active, + operational_state: OperationalState::Available, }; // Valid transition assert!(validate_action_state_compatibility( &VfAction::Transfer, - &resource.state + &resource.operational_state ).is_ok()); // Invalid transition assert!(validate_action_state_compatibility( &VfAction::Use, - &ResourceState::Reserved + &OperationalState::Reserved ).is_err()); } } diff --git a/documentation/specifications/ndo-v1-architecture-design.md b/documentation/specifications/ndo-v1-architecture-design.md index ef2a4fc..bc213e7 100644 --- a/documentation/specifications/ndo-v1-architecture-design.md +++ b/documentation/specifications/ndo-v1-architecture-design.md @@ -245,7 +245,7 @@ pub struct EconomicResource { pub conforms_to: ActionHash, // → ResourceSpecification (required, embedded) pub current_location: Option, // NDO-specific: - pub state: OperationalState, // Was: ResourceState (now typed correctly) + pub operational_state: OperationalState, // Process condition on instance (REQ-NDO-OS-01) pub tracking_identifier: Option, // Serial number, QR code, etc. } diff --git a/documentation/specifications/protocol-bridge-specifications.md b/documentation/specifications/protocol-bridge-specifications.md index 23a78d3..675b692 100644 --- a/documentation/specifications/protocol-bridge-specifications.md +++ b/documentation/specifications/protocol-bridge-specifications.md @@ -403,7 +403,8 @@ Pydantic/JSON field names **must match Rust zome field names exactly** (Holochai **Enum Values (PascalCase strings):** -- `ResourceState`: `"PendingValidation"`, `"Active"`, `"Maintenance"`, `"Retired"`, `"Reserved"` +- `OperationalState`: `"PendingValidation"`, `"Available"`, `"Reserved"`, `"InTransit"`, `"InStorage"`, `"InMaintenance"`, `"InUse"` +- `LifecycleStage` (on `NondominiumIdentity`): `"Ideation"`, `"Specification"`, … through `"EndOfLife"` - `VfAction`: 16 variants — `"Transfer"`, `"Use"`, `"InitialTransfer"`, `"TransferCustody"`, etc. - `ParticipationClaimType`: 16 variants — `"ResourceProvider"`, `"ResourceReceiver"`, `"Custodian"`, etc. diff --git a/documentation/zomes/architecture_overview.md b/documentation/zomes/architecture_overview.md index 178d4d6..c992d5a 100644 --- a/documentation/zomes/architecture_overview.md +++ b/documentation/zomes/architecture_overview.md @@ -754,8 +754,7 @@ pub struct EconomicResource { pub unit: String, // Standard measurement unit pub custodian: AgentPubKey, // Primary Accountable Agent pub current_location: Option, // Resource location tracking - // TODO: split into LifecycleStage (NondominiumIdentity Layer 0) + OperationalState (EconomicResource Layer 2) - pub state: ResourceState, // Currently conflated; pending split per ndo_prima_materia.md Section 5 + pub operational_state: OperationalState, // Process condition (Layer 2 instance); lifecycle on NondominiumIdentity pub governance_rules: Vec, // Embedded governance pub validation_status: String, // Peer validation status pub process_history: Vec, // Economic Process audit trail diff --git a/documentation/zomes/resource_zome.md b/documentation/zomes/resource_zome.md index 8116ac9..ce06d24 100644 --- a/documentation/zomes/resource_zome.md +++ b/documentation/zomes/resource_zome.md @@ -135,57 +135,37 @@ pub struct EconomicResource { pub created_by: AgentPubKey, // Resource creator pub created_at: Timestamp, // Creation timestamp pub current_location: Option, // Physical/virtual location - // TODO: split into two fields: - // pub lifecycle_stage: LifecycleStage, // lives on NondominiumIdentity (Layer 0) - // pub operational_state: OperationalState, // lives on EconomicResource (Layer 2) - pub state: ResourceState, // Current resource state (pending split — see ndo_prima_materia.md Section 5) + pub operational_state: OperationalState, // Layer 2 process condition (REQ-NDO-OS-01 ✅) } ``` **ValueFlows**: Compliant economic resource implementation **Custody**: Clear custodianship with Primary Accountable Agent pattern -**State Management**: Comprehensive resource lifecycle tracking +**State Management**: Operational condition on instance; lifecycle maturity on `NondominiumIdentity` -### ResourceState Enum (pending replacement) - -> **TODO**: Split `ResourceState` into two orthogonal enums per `ndo_prima_materia.md` Section 5 and `REQ-NDO-OS-01` through `REQ-NDO-OS-06`. +### OperationalState Enum ```rust -// CURRENT (conflated — to be replaced): -pub enum ResourceState { - PendingValidation, // → OperationalState::PendingValidation - Active, // → LifecycleStage::Active + OperationalState::Available - Maintenance, // → OperationalState::InMaintenance (LifecycleStage unchanged) - Retired, // → LifecycleStage::Deprecated or EndOfLife - Reserved, // → OperationalState::Reserved (LifecycleStage unchanged) -} - -// IMPLEMENTED — LifecycleStage (on NondominiumIdentity, Layer 0, REQ-NDO-LC-01–07): -pub enum LifecycleStage { - Ideation, // spark of an idea, Layer 0 anchor only - Specification, // design/requirements being written - Development, // active construction / prototyping - Prototype, // proof-of-concept, not yet production-ready - Stable, // production-ready, design is replicable - Distributed, // being actively fabricated/used across the network - Active, // in normal use - Hibernating, // dormant but recoverable (reversible) - Deprecated, // superseded; successor NDO required - EndOfLife, // permanently concluded; Layer 0 tombstone -} - -// TARGET — OperationalState (on EconomicResource, Layer 2): pub enum OperationalState { - PendingValidation, Available, Reserved, - InTransit, InStorage, InMaintenance, InUse, + Available, + Reserved, + InTransit, + InStorage, + InMaintenance, + InUse, + PendingValidation, // default for newly created instances } ``` **Key principle**: Transport, storage, and maintenance are *processes* that act on a resource at *any* lifecycle stage. A `Development` resource can be `InTransit` between R&D labs. An `Active` resource can be `InMaintenance`. These are operational conditions, not lifecycle milestones. -**Lifecycle**: `LifecycleStage` tracks maturity/evolution (advances rarely, almost irreversibly) -**Operational**: `OperationalState` tracks active processes (cycles frequently, reset to `Available` when process ends) -**Transitions**: All state changes governed by the governance zome; each transition references a valid `EconomicEvent` +### LifecycleStage vs OperationalState + +**Lifecycle** (`LifecycleStage` on `NondominiumIdentity`): maturity/evolution (advances rarely, almost irreversibly). Faceted discovery via `NdoByLifecycleStage`. + +**Operational** (`OperationalState` on `EconomicResource`): active process condition (cycles frequently; typically resets to `Available` when a process ends). Faceted discovery via `ResourcesByOperationalState`. + +**Governance transitions** (REQ-NDO-OS-02/03): deferred — interim writes use `update_operational_state` in `zome_resource`; future governance-zome ownership will require valid `EconomicEvent` references. ### GovernanceRule Entry @@ -457,28 +437,25 @@ pub struct TransferCustodyInput { - Creates economic event (TransferCustody) - Triggers validation workflow if required -#### `update_resource_state(input: UpdateResourceStateInput) -> ExternResult` - -> **TODO**: Replace with two separate functions per `REQ-NDO-OS-01`: -> - `update_lifecycle_stage(input: UpdateLifecycleStageInput)` — transitions on `NondominiumIdentity`; requires an `EconomicEvent` hash as proof of triggering action -> - `update_operational_state(input: UpdateOperationalStateInput)` — transitions on `EconomicResource`; called by governance zome when processes begin/end +#### `update_operational_state(input: UpdateOperationalStateInput) -> ExternResult` -Updates the state of an economic resource. +Updates the operational state of an `EconomicResource` instance (REQ-NDO-OS-01). Lifecycle maturity transitions use `update_lifecycle_stage` on `NondominiumIdentity` (Layer 0). **Input**: ```rust -// CURRENT (pending split): -pub struct UpdateResourceStateInput { +pub struct UpdateOperationalStateInput { pub resource_hash: ActionHash, - pub new_state: ResourceState, // TODO: split into lifecycle_stage / operational_state - pub reason: Option, + pub new_operational_state: OperationalState, } ``` -**Authorization**: Governance zome only (via governance-as-operator pattern) -**Validation**: All transitions require a corresponding `EconomicEvent` reference -**Integration**: Creates economic events for PPR generation +**Authorization**: Current agent (interim resource-zome writer; governance-zome ownership deferred per REQ-NDO-OS-02) +**Side effects**: Moves the `ResourcesByOperationalState` anchor link when the state changes + +#### `get_resources_by_operational_state(state: OperationalState) -> ExternResult>` + +Discovery via `ResourcesByOperationalState` anchor (`ndo.opstate.{state}`). Parallels `get_ndos_by_lifecycle_stage`. ### Governance Rule Management diff --git a/packages/shared-types/src/resource.types.ts b/packages/shared-types/src/resource.types.ts index 8cd2088..bf643ad 100644 --- a/packages/shared-types/src/resource.types.ts +++ b/packages/shared-types/src/resource.types.ts @@ -1,12 +1,14 @@ import type { ActionHash, AgentPubKey, EntryHash, Record, Timestamp } from '@holochain/client'; -// Resource State Types -export type ResourceState = - | "PendingValidation" - | "Active" - | "Maintenance" - | "Retired" - | "Reserved"; +// Resource operational state types (Layer 2 instance condition) +export type OperationalState = + | "Available" + | "Reserved" + | "InTransit" + | "InStorage" + | "InMaintenance" + | "InUse" + | "PendingValidation"; // Core Resource Types export interface ResourceSpecification { @@ -25,7 +27,7 @@ export interface EconomicResource { unit: string; custodian: AgentPubKey; current_location?: string; - state: ResourceState; + operational_state: OperationalState; } // Governance Types @@ -255,6 +257,11 @@ export interface TransferCustodyOutput { updated_resource: EconomicResource; } +export interface UpdateOperationalStateInput { + resource_hash: ActionHash; + new_operational_state: OperationalState; +} + // Zome Function Types export interface ResourceZomeFunctions { create_resource_specification: ( diff --git a/pai/cursor-rules/10-domain-enums.md b/pai/cursor-rules/10-domain-enums.md index d01bf6c..7ff78a0 100644 --- a/pai/cursor-rules/10-domain-enums.md +++ b/pai/cursor-rules/10-domain-enums.md @@ -68,9 +68,8 @@ pub enum LifecycleStage { Transitions are governance-validated (governance zome as state transition operator). At `EndOfLife`, only Layer 0 survives as a permanent tombstone. -## OperationalState Enum (7 states — planned, not yet in code) -Source: `documentation/requirements/ndo_prima_materia.md §5` -Note: currently `ResourceState` in `zome_resource/src/lib.rs` — refactor tracked as REQ-NDO-OS-06 +## OperationalState Enum (7 states — implemented on EconomicResource) +Source: `documentation/requirements/ndo_prima_materia.md §5`, `crates/shared/src/types.rs` ```rust pub enum OperationalState { @@ -85,7 +84,7 @@ pub enum OperationalState { ``` Orthogonal to `LifecycleStage`: an `Active`-stage resource can be `InMaintenance`; -a `Prototype` can be `InTransit`. The split fixes the current `ResourceState` conflation. +a `Prototype` can be `InTransit`. Lifecycle maturity remains on `NondominiumIdentity` (`LifecycleStage`). ## VfAction Enum (16 actions) Source: `documentation/specifications/specifications.md §3.3.1` diff --git a/tests/src/nondominium/resource/common.ts b/tests/src/nondominium/resource/common.ts index 930d450..f2d7f9e 100644 --- a/tests/src/nondominium/resource/common.ts +++ b/tests/src/nondominium/resource/common.ts @@ -18,7 +18,7 @@ import { GetAllEconomicResourcesOutput, GetAllGovernanceRulesOutput, GetResourceSpecWithRulesOutput, - ResourceState, + OperationalState, TransferCustodyInput, TransferCustodyOutput, } from "@nondominium/shared-types"; @@ -185,17 +185,20 @@ export async function transferCustody( }); } -export async function updateResourceState( +export async function updateOperationalState( cell: CallableCell, - input: { resource_hash: ActionHash; new_state: ResourceState }, + input: { resource_hash: ActionHash; new_operational_state: OperationalState }, ): Promise { return cell.callZome({ zome_name: "zome_resource", - fn_name: "update_resource_state", + fn_name: "update_operational_state", payload: input, }); } +/** @deprecated Use updateOperationalState */ +export const updateResourceState = updateOperationalState; + export async function getAgentEconomicResources( cell: CallableCell, agent_pubkey: AgentPubKey, @@ -463,15 +466,24 @@ export async function setupGovernanceRules( }; } -// Resource state constants for testing -export const RESOURCE_STATES: Record = { +// Operational state constants for testing (Layer 2 EconomicResource) +export const OPERATIONAL_STATES: Record = { PENDING: "PendingValidation", - ACTIVE: "Active", - MAINTENANCE: "Maintenance", - RETIRED: "Retired", + AVAILABLE: "Available", + IN_MAINTENANCE: "InMaintenance", + IN_USE: "InUse", RESERVED: "Reserved", }; +/** @deprecated Use OPERATIONAL_STATES */ +export const RESOURCE_STATES = { + PENDING: OPERATIONAL_STATES.PENDING, + ACTIVE: OPERATIONAL_STATES.AVAILABLE, + MAINTENANCE: OPERATIONAL_STATES.IN_MAINTENANCE, + RETIRED: OPERATIONAL_STATES.AVAILABLE, + RESERVED: OPERATIONAL_STATES.RESERVED, +} as const; + export const TEST_CATEGORIES = { TOOLS: "tools", EQUIPMENT: "equipment", diff --git a/tests/src/nondominium/resource/resource-foundation-tests.test.ts b/tests/src/nondominium/resource/resource-foundation-tests.test.ts index 4f6ef0c..51c3cfe 100644 --- a/tests/src/nondominium/resource/resource-foundation-tests.test.ts +++ b/tests/src/nondominium/resource/resource-foundation-tests.test.ts @@ -160,8 +160,8 @@ test("Economic Resource Foundation: Create and manage economic resources", async } // Verify resource state is correct - if (resource.state !== RESOURCE_STATES.PENDING) { - throw new Error(`Expected state ${RESOURCE_STATES.PENDING}, got ${resource.state}`); + if (resource.operational_state !== RESOURCE_STATES.PENDING) { + throw new Error(`Expected state ${RESOURCE_STATES.PENDING}, got ${resource.operational_state}`); } // Verify custodian is set correctly @@ -170,7 +170,7 @@ test("Economic Resource Foundation: Create and manage economic resources", async throw new Error("Custodian not set correctly"); } - console.log(`✅ Economic resource created successfully in state: ${resource.state}`); + console.log(`✅ Economic resource created successfully in state: ${resource.operational_state}`); // Test retrieval of all resources await dhtSync([lynn, bob], lynn.cells[0].cell_id[0]); diff --git a/tests/src/nondominium/resource/resource-integration-tests.test.ts b/tests/src/nondominium/resource/resource-integration-tests.test.ts index b1798d1..5d6d9ff 100644 --- a/tests/src/nondominium/resource/resource-integration-tests.test.ts +++ b/tests/src/nondominium/resource/resource-integration-tests.test.ts @@ -261,7 +261,7 @@ test("resource state management across agents", async () => { // Lynn updates her resource state const stateUpdateResult = await updateResourceState(lynn.cells[0], { resource_hash: context.lynnResourceHash!, - new_state: RESOURCE_STATES.ACTIVE, + new_operational_state: RESOURCE_STATES.ACTIVE, }); assert.ok(stateUpdateResult); @@ -289,7 +289,7 @@ test("resource state management across agents", async () => { // Test state transition to maintenance await updateResourceState(lynn.cells[0], { resource_hash: context.lynnResourceHash!, - new_state: RESOURCE_STATES.MAINTENANCE, + new_operational_state: RESOURCE_STATES.MAINTENANCE, }); await dhtSync([lynn, bob], lynn.cells[0].cell_id[0]); diff --git a/tests/src/nondominium/resource/resource-scenario-tests.test.ts b/tests/src/nondominium/resource/resource-scenario-tests.test.ts index 8c93520..1d9853b 100644 --- a/tests/src/nondominium/resource/resource-scenario-tests.test.ts +++ b/tests/src/nondominium/resource/resource-scenario-tests.test.ts @@ -138,7 +138,7 @@ test( console.log( `✅ Created economic resource: ${printerResource.resource_hash}`, ); - assert.equal(printerResource.resource.state, RESOURCE_STATES.PENDING); + assert.equal(printerResource.resource.operational_state, RESOURCE_STATES.PENDING); assert.equal( printerResource.resource.custodian.toString(), lynn.agentPubKey.toString(), @@ -152,7 +152,7 @@ test( // Lynn validates and activates the resource const activationResult = await updateResourceState(lynn.cells[0], { resource_hash: printerResource.resource_hash, - new_state: RESOURCE_STATES.ACTIVE, + new_operational_state: RESOURCE_STATES.ACTIVE, }); assert.ok(activationResult); @@ -216,7 +216,7 @@ test( // Bob performs maintenance const maintenanceResult = await updateResourceState(bob.cells[0], { resource_hash: custodyTransfer.updated_resource_hash, - new_state: RESOURCE_STATES.MAINTENANCE, + new_operational_state: RESOURCE_STATES.MAINTENANCE, }); assert.ok(maintenanceResult); @@ -239,7 +239,7 @@ test( // Return to active state after maintenance await updateResourceState(bob.cells[0], { resource_hash: custodyTransfer.updated_resource_hash, - new_state: RESOURCE_STATES.ACTIVE, + new_operational_state: RESOURCE_STATES.ACTIVE, }); await dhtSync([lynn, bob], lynn.cells[0].cell_id[0]); @@ -501,28 +501,28 @@ test( // Activate resources sequentially to avoid source chain conflicts await updateResourceState(lynn.cells[0], { resource_hash: spaceResource.resource_hash, - new_state: RESOURCE_STATES.ACTIVE, + new_operational_state: RESOURCE_STATES.ACTIVE, }); await new Promise((resolve) => setTimeout(resolve, 100)); await updateResourceState(lynn.cells[0], { resource_hash: toolsResource.resource_hash, - new_state: RESOURCE_STATES.ACTIVE, + new_operational_state: RESOURCE_STATES.ACTIVE, }); await new Promise((resolve) => setTimeout(resolve, 100)); await updateResourceState(bob.cells[0], { resource_hash: printingResource.resource_hash, - new_state: RESOURCE_STATES.ACTIVE, + new_operational_state: RESOURCE_STATES.ACTIVE, }); await new Promise((resolve) => setTimeout(resolve, 100)); await updateResourceState(bob.cells[0], { resource_hash: electronicsResource.resource_hash, - new_state: RESOURCE_STATES.ACTIVE, + new_operational_state: RESOURCE_STATES.ACTIVE, }); await dhtSync([lynn, bob], lynn.cells[0].cell_id[0]); @@ -742,7 +742,7 @@ test( const activationResult = await updateResourceState(bob.cells[0], { resource_hash: initialTransfer.updated_resource_hash, - new_state: RESOURCE_STATES.ACTIVE, + new_operational_state: RESOURCE_STATES.ACTIVE, }); assert.ok(activationResult); @@ -771,7 +771,7 @@ test( // Bob performs scheduled maintenance const maintenanceStart = await updateResourceState(bob.cells[0], { resource_hash: activationResult.signed_action.hashed.hash, - new_state: RESOURCE_STATES.MAINTENANCE, + new_operational_state: RESOURCE_STATES.MAINTENANCE, }); assert.ok(maintenanceStart); @@ -792,7 +792,7 @@ test( // Complete maintenance and return to active const maintenanceComplete = await updateResourceState(bob.cells[0], { resource_hash: maintenanceStart.signed_action.hashed.hash, - new_state: RESOURCE_STATES.ACTIVE, + new_operational_state: RESOURCE_STATES.ACTIVE, }); await dhtSync([lynn, bob], lynn.cells[0].cell_id[0]); @@ -1078,28 +1078,28 @@ test( // Update resource states sequentially to avoid source chain conflicts await updateResourceState(lynn.cells[0], { resource_hash: courseResource.resource_hash, - new_state: RESOURCE_STATES.ACTIVE, + new_operational_state: RESOURCE_STATES.ACTIVE, }); await new Promise((resolve) => setTimeout(resolve, 100)); await updateResourceState(lynn.cells[0], { resource_hash: kitchenResource.resource_hash, - new_state: RESOURCE_STATES.MAINTENANCE, // Kitchen under renovation + new_operational_state: RESOURCE_STATES.MAINTENANCE, // Kitchen under renovation }); await new Promise((resolve) => setTimeout(resolve, 100)); await updateResourceState(bob.cells[0], { resource_hash: webDevResource.resource_hash, - new_state: RESOURCE_STATES.ACTIVE, + new_operational_state: RESOURCE_STATES.ACTIVE, }); await new Promise((resolve) => setTimeout(resolve, 100)); await updateResourceState(bob.cells[0], { resource_hash: vanResource.resource_hash, - new_state: RESOURCE_STATES.RESERVED, // Vans reserved for special project + new_operational_state: RESOURCE_STATES.RESERVED, // Vans reserved for special project }); await dhtSync([lynn, bob], lynn.cells[0].cell_id[0]); diff --git a/tests/src/nondominium/resource/resource-update-test.test.ts b/tests/src/nondominium/resource/resource-update-test.test.ts index 2bffb54..5752a68 100644 --- a/tests/src/nondominium/resource/resource-update-test.test.ts +++ b/tests/src/nondominium/resource/resource-update-test.test.ts @@ -58,10 +58,10 @@ test("basic resource state update", async () => { console.log( `✅ Created economic resource: ${testResource.resource_hash}`, ); - console.log(`Initial state: ${testResource.resource.state}`); + console.log(`Initial state: ${testResource.resource.operational_state}`); // Verify initial state is PendingValidation - assert.equal(testResource.resource.state, RESOURCE_STATES.PENDING); + assert.equal(testResource.resource.operational_state, RESOURCE_STATES.PENDING); assert.equal( testResource.resource.custodian.toString(), lynn.agentPubKey.toString(), @@ -73,7 +73,7 @@ test("basic resource state update", async () => { console.log("Step 3: Lynn activates the resource"); const activationResult = await updateResourceState(lynn.cells[0], { resource_hash: testResource.resource_hash, - new_state: RESOURCE_STATES.ACTIVE, + new_operational_state: RESOURCE_STATES.ACTIVE, }); console.log(`✅ Resource activation call completed`); diff --git a/ui/src/lib/components/ndo/ResourcesTab.svelte b/ui/src/lib/components/ndo/ResourcesTab.svelte index dff0a25..5ea1eba 100644 --- a/ui/src/lib/components/ndo/ResourcesTab.svelte +++ b/ui/src/lib/components/ndo/ResourcesTab.svelte @@ -1,6 +1,7 @@ -
-

Economic events

-

- Events are loaded per inventoried resource (`get_events_for_resource`) for all instances of this - specification. -

+{#if showCommitment && canAct} + { + showCommitment = false; + }} + oncreated={() => { + void load(); + }} + /> +{/if} + +{#if showEvent && canAct} + { + showEvent = false; + }} + oncreated={() => { + void load(); + }} + /> +{/if} + +
+
+
+

Activity

+

+ Commitments and events for this NDO (client-filtered by ndo_identity_hash). +

+
+
+ + +
+
+ {#if loadError}

{loadError}

- {:else if events.length === 0} -

No events recorded for resources under this specification.

- {:else} -
    - {#each events as ev, i (i)} -
  • -
    {ev.action}
    -
    - Qty {ev.resource_quantity} · {new Date(Number(ev.event_time) / 1000).toLocaleString()} -
    - {#if ev.note} -
    {ev.note}
    - {/if} -
  • - {/each} -
{/if} + +
+

Commitments

+ {#if ndoCommitments.length === 0} +

No commitments for this NDO yet.

+ {:else} +
    + {#each ndoCommitments as c, i (i)} +
  • +
    {c.action}
    +
    + Due {new Date(Number(c.due_date) / 1000).toLocaleString()} +
    + {#if c.note} +
    {c.note}
    + {/if} +
  • + {/each} +
+ {/if} +
+ +
+

Economic events

+ {#if ndoEvents.length === 0} +

No events recorded for this NDO yet.

+ {:else} +
    + {#each ndoEvents as ev, i (i)} +
  • +
    {ev.action}
    +
    + Qty {ev.resource_quantity} · {new Date(Number(ev.event_time) / 1000).toLocaleString()} +
    + {#if ev.note} +
    {ev.note}
    + {/if} +
  • + {/each} +
+ {/if} +
diff --git a/ui/src/lib/components/ndo/CommitmentCreateForm.svelte b/ui/src/lib/components/ndo/CommitmentCreateForm.svelte new file mode 100644 index 0000000..15cebf0 --- /dev/null +++ b/ui/src/lib/components/ndo/CommitmentCreateForm.svelte @@ -0,0 +1,223 @@ + + +
+ +
diff --git a/ui/src/lib/components/ndo/EconomicEventCreateForm.svelte b/ui/src/lib/components/ndo/EconomicEventCreateForm.svelte new file mode 100644 index 0000000..9c0c915 --- /dev/null +++ b/ui/src/lib/components/ndo/EconomicEventCreateForm.svelte @@ -0,0 +1,263 @@ + + +
+ +
diff --git a/ui/src/lib/components/ndo/GovernanceTab.svelte b/ui/src/lib/components/ndo/GovernanceTab.svelte index 1ae2c85..ff273c5 100644 --- a/ui/src/lib/components/ndo/GovernanceTab.svelte +++ b/ui/src/lib/components/ndo/GovernanceTab.svelte @@ -1,37 +1,91 @@ +{#if showRuleEditor && canCreateRule} + { + showRuleEditor = false; + editorSpecHash = undefined; + }} + oncreated={() => { + void loadRules(); + }} + /> +{/if} +
-

Governance rules (resource zome)

- {#if rules.length === 0} -

No governance rules linked to this specification.

+
+

Governance rules

+ +
+ + {#if loadMessage && rules.length === 0} +

{loadMessage}

+ {:else if rules.length === 0} +

No governance rules linked to this NDO’s specifications.

{:else}
    - {#each rules as rule, i (i)} + {#each rules as item, i (i)} + {@const kind = ruleTypeLabel(item.rule.rule_data)} + {@const payload = rulePayload(item.rule.rule_data)}
  • -
    {rule.rule_type}
    -
    {rule.rule_data}
    - {#if rule.enforced_by} -
    Enforced by: {rule.enforced_by}
    +
    +
    {kind}
    +
    spec: {item.specName}
    +
    +
    + {#each Object.entries(payload) as [k, v] (k)} +
    + {k}: + {v === undefined || v === null || v === '' ? '—' : String(v)} +
    + {/each} +
    + {#if item.rule.enforced_by} +
    Enforced by: {item.rule.enforced_by}
    {/if}
  • {/each} @@ -87,9 +194,11 @@ {/each}
- + {/if}
diff --git a/ui/src/lib/components/ndo/NdoIdentityLayer.svelte b/ui/src/lib/components/ndo/NdoIdentityLayer.svelte index 448edc6..84d6b13 100644 --- a/ui/src/lib/components/ndo/NdoIdentityLayer.svelte +++ b/ui/src/lib/components/ndo/NdoIdentityLayer.svelte @@ -8,6 +8,8 @@ import { PersonServiceTag, PersonServiceResolved } from '$lib/services/zomes/person.service'; import LifecycleTransitionModal from './LifecycleTransitionModal.svelte'; import TransitionHistoryPanel from './TransitionHistoryPanel.svelte'; + import { effectiveRivalryLabel } from '$lib/utils/rivalry'; + import type { ResourceNature } from '@nondominium/shared-types'; interface Props { descriptor: NdoDescriptor | null; @@ -35,8 +37,11 @@ const regimeColorMap: Record = { Private: 'bg-gray-100 text-gray-600', Commons: 'bg-cyan-100 text-cyan-700', - Nondominium: 'bg-emerald-100 text-emerald-700', - CommonPool: 'bg-rose-100 text-rose-700' + Collective: 'bg-violet-100 text-violet-700', + Pool: 'bg-amber-100 text-amber-700', + CommonPool: 'bg-rose-100 text-rose-700', + Public: 'bg-sky-100 text-sky-700', + Nondominium: 'bg-emerald-100 text-emerald-700' }; const natureColorMap: Record = { @@ -51,6 +56,13 @@ return value ? (map[value] ?? 'bg-gray-100 text-gray-600') : 'bg-gray-100 text-gray-400'; } + const rivalryBadge = $derived( + effectiveRivalryLabel( + descriptor?.resource_nature as ResourceNature | null, + descriptor?.rivalry_override + ) + ); + const formattedDate = $derived( descriptor?.created_at ? new Date(descriptor.created_at / 1000).toLocaleString() : null ); @@ -133,6 +145,11 @@ {descriptor.resource_nature} {/if} + {#if rivalryBadge} + + {rivalryBadge} + + {/if}
diff --git a/ui/src/lib/components/ndo/NdoView.svelte b/ui/src/lib/components/ndo/NdoView.svelte index 437d2b8..d13a3c3 100644 --- a/ui/src/lib/components/ndo/NdoView.svelte +++ b/ui/src/lib/components/ndo/NdoView.svelte @@ -333,13 +333,23 @@
{#if tab === 'resources'} - + {:else if tab === 'governance'} - + {:else if tab === 'composition'} {:else} - + {/if}
{/if} diff --git a/ui/src/lib/components/ndo/ResourcesTab.svelte b/ui/src/lib/components/ndo/ResourcesTab.svelte index 5ea1eba..93bedac 100644 --- a/ui/src/lib/components/ndo/ResourcesTab.svelte +++ b/ui/src/lib/components/ndo/ResourcesTab.svelte @@ -1,92 +1,137 @@ -
-

Specification

-

{specName}

+{#if showCreateModal} + { + showCreateModal = false; + }} + oncreated={() => { + void load(); + }} + /> +{/if} -

All resource specifications

-
- - - - - - - - - - {#each resourceStore.resourceSpecificationListings as listing (listing.action_hash.toString())} - - - - - - {/each} - -
NameCategoryActive
{listing.specification.name}{listing.specification.category ?? '—'}{listing.specification.is_active !== false ? 'yes' : 'no'}
+
+
+
+

Layer 1 specifications

+

Resource specifications linked to this NDO.

+
+
-

Economic resources (this spec)

+ {#if !canCreateSpec} +

+ Layer 1 activation is blocked while the NDO is {lifecycleStage}. Advance the + lifecycle first. +

+ {/if} + {#if loadError}

{loadError}

- {:else if instances.length === 0} -

No inventoried resources for this specification yet.

+ {:else if listings.length === 0} +

No resource specifications for this NDO yet.

{:else} -
    - {#each instances as row, i (i)} -
  • - Qty {row.resource.quantity} {row.resource.unit} · - Operational state - {operationalStateLabel(row.resource.operational_state)} -
  • +
    + {#each listings as listing (listing.action_hash.toString())} + {@const instances = instancesBySpec.get(listing.action_hash.toString()) ?? []} +
    +
    +
    +
    {listing.specification.name}
    +
    + {listing.specification.category ?? '—'} · scope + {listing.specification.scope ?? '—'} · + {listing.specification.is_active !== false ? 'active' : 'inactive'} +
    + {#if listing.specification.description} +

    {listing.specification.description}

    + {/if} +
    +
    + +

    + Economic resources +

    + {#if instances.length === 0} +

    No inventoried resources for this specification.

    + {:else} +
      + {#each instances as row, i (i)} +
    • + Qty {row.resource.quantity} + {row.resource.unit} · + Operational state + {operationalStateLabel(row.resource.operational_state)} +
    • + {/each} +
    + {/if} +
    {/each} -
+
{/if}
diff --git a/ui/src/lib/components/ndo/RuleEditorModal.svelte b/ui/src/lib/components/ndo/RuleEditorModal.svelte new file mode 100644 index 0000000..2ae05e2 --- /dev/null +++ b/ui/src/lib/components/ndo/RuleEditorModal.svelte @@ -0,0 +1,299 @@ + + +
+ +
diff --git a/ui/src/lib/components/ndo/SpecificationCreateModal.svelte b/ui/src/lib/components/ndo/SpecificationCreateModal.svelte new file mode 100644 index 0000000..938d793 --- /dev/null +++ b/ui/src/lib/components/ndo/SpecificationCreateModal.svelte @@ -0,0 +1,175 @@ + + +
+ +
diff --git a/ui/src/lib/errors/error-contexts.ts b/ui/src/lib/errors/error-contexts.ts index 111759d..9d55210 100644 --- a/ui/src/lib/errors/error-contexts.ts +++ b/ui/src/lib/errors/error-contexts.ts @@ -53,7 +53,9 @@ export const RESOURCE_CONTEXTS = { GET_NDOS_BY_PROPERTY_REGIME: 'Failed to get NDOs by property regime', GET_NDO_TRANSITION_HISTORY: 'Failed to get NDO transition history', UPDATE_OPERATIONAL_STATE: 'Failed to update economic resource operational state', - GET_RESOURCES_BY_OPERATIONAL_STATE: 'Failed to get resources by operational state' + GET_RESOURCES_BY_OPERATIONAL_STATE: 'Failed to get resources by operational state', + GET_SPECIFICATIONS_FOR_NDO: 'Failed to get resource specifications for NDO', + CHECK_RULE_DATA_CONSTRAINTS: 'Failed to check rule data constraints' } as const; export const GOVERNANCE_CONTEXTS = { @@ -82,6 +84,7 @@ export const GOVERNANCE_CONTEXTS = { GET_VALIDATION_HISTORY: 'Failed to get validation history', EVALUATE_STATE_TRANSITION: 'Failed to evaluate state transition', VALIDATE_GOVERNANCE_RULES: 'Failed to validate governance rules', + CHECK_ACTION_CONSTRAINTS: 'Failed to check action constraints', LOG_INITIAL_TRANSFER: 'Failed to log initial transfer', CREATE_DISPUTE: 'Failed to create dispute', VOTE_ON_DISPUTE: 'Failed to vote on dispute' diff --git a/ui/src/lib/schemas/ndo.schemas.ts b/ui/src/lib/schemas/ndo.schemas.ts index 80ebd45..48b1423 100644 --- a/ui/src/lib/schemas/ndo.schemas.ts +++ b/ui/src/lib/schemas/ndo.schemas.ts @@ -10,7 +10,8 @@ export class NdoDescriptor extends Schema.Class('NdoDescriptor')( initiator: Schema.NullOr(Schema.String), created_at: Schema.NullOr(Schema.Number), successor_ndo_hash: Schema.NullOr(Schema.String), - hibernation_origin: Schema.NullOr(Schema.String) + hibernation_origin: Schema.NullOr(Schema.String), + rivalry_override: Schema.NullOr(Schema.String) }) {} export class GroupDescriptor extends Schema.Class('GroupDescriptor')({ diff --git a/ui/src/lib/schemas/resource.schemas.ts b/ui/src/lib/schemas/resource.schemas.ts index 4439cfb..af5277a 100644 --- a/ui/src/lib/schemas/resource.schemas.ts +++ b/ui/src/lib/schemas/resource.schemas.ts @@ -28,6 +28,7 @@ export const PropertyRegimeSchema = Schema.Literal( 'Collective', 'Pool', 'CommonPool', + 'Public', 'Nondominium' ); export type PropertyRegime = Schema.Schema.Type; @@ -61,7 +62,9 @@ export class ResourceSpecInput extends Schema.Class('Resource category: Schema.String, image_url: Schema.optional(Schema.String), tags: Schema.Array(Schema.String), - is_active: Schema.Boolean + is_active: Schema.Boolean, + scope: Schema.Literal('Project', 'Network', 'Public'), + ndo_identity_hash: Schema.Any // ActionHash }) { } export class UIResourceSpec extends Schema.Class('UIResourceSpec')({ @@ -71,6 +74,8 @@ export class UIResourceSpec extends Schema.Class('UIResourceSpec image_url: Schema.optional(Schema.String), tags: Schema.Array(Schema.String), is_active: Schema.Boolean, + scope: Schema.optional(Schema.Literal('Project', 'Network', 'Public')), + ndo_identity_hash: Schema.optional(Schema.Any), original_action_hash: Schema.optional(Schema.Any), // ActionHash created_at: Schema.optional(Schema.Number) }) { } @@ -95,16 +100,67 @@ export class UIEconomicResource extends Schema.Class('UIEcon created_at: Schema.optional(Schema.Number) }) { } +export const RivalrySchema = Schema.Literal('Rivalrous', 'NonRivalrous'); +export type Rivalry = Schema.Schema.Type; + +export const ResourceScopeSchema = Schema.Literal('Project', 'Network', 'Public'); +export type ResourceScope = Schema.Schema.Type; + +export const AccessibilitySchema = Schema.Literal('Free', 'Credentialed', 'Gated'); +export const TransferTypeSchema = Schema.Literal( + 'Ownership', + 'Custody', + 'UseRights', + 'Benefit' +); + +/** Externally-tagged RuleData — mirrors Rust `RuleData`. */ +export const RuleDataSchema = Schema.Union( + Schema.Struct({ + AccessRequirement: Schema.Struct({ + accessibility: AccessibilitySchema, + required_role: Schema.optional(Schema.String), + min_affiliation: Schema.optional(Schema.String) + }) + }), + Schema.Struct({ + UsageLimit: Schema.Struct({ + max_duration_hours: Schema.optional(Schema.Number), + max_quantity_per_period: Schema.optional(Schema.Number), + period_days: Schema.optional(Schema.Number) + }) + }), + Schema.Struct({ + TransferCondition: Schema.Struct({ + transfer_type: TransferTypeSchema, + requires_validation: Schema.Boolean, + validator_role: Schema.optional(Schema.String) + }) + }), + Schema.Struct({ + MaintenanceSchedule: Schema.Struct({ + interval_days: Schema.Number, + required_role: Schema.optional(Schema.String) + }) + }) +); + export class GovernanceRuleInput extends Schema.Class('GovernanceRuleInput')({ - rule_type: Schema.String, - rule_data: Schema.String, // JSON-encoded - enforced_by: Schema.optional(Schema.String) + rule_data: RuleDataSchema, + enforced_by: Schema.optional(Schema.String), + ndo_identity_hash: Schema.Any, // ActionHash + property_regime: PropertyRegimeSchema, + resource_nature: ResourceNatureSchema, + rivalry_override: Schema.optional(RivalrySchema) }) { } export class UIGovernanceRule extends Schema.Class('UIGovernanceRule')({ - rule_type: Schema.String, - rule_data: Schema.String, + rule_data: RuleDataSchema, enforced_by: Schema.optional(Schema.String), + ndo_identity_hash: Schema.Any, + property_regime: PropertyRegimeSchema, + resource_nature: ResourceNatureSchema, + rivalry_override: Schema.optional(RivalrySchema), original_action_hash: Schema.optional(Schema.Any), created_at: Schema.optional(Schema.Number) }) { } @@ -114,7 +170,8 @@ export class NdoIdentityInput extends Schema.Class('NdoIdentit description: Schema.optional(Schema.String), property_regime: PropertyRegimeSchema, resource_nature: ResourceNatureSchema, - lifecycle_stage: LifecycleStageSchema + lifecycle_stage: LifecycleStageSchema, + rivalry_override: Schema.optional(RivalrySchema) }) { } export class UINdoIdentity extends Schema.Class('UINdoIdentity')({ @@ -125,6 +182,7 @@ export class UINdoIdentity extends Schema.Class('UINdoIdentity')( lifecycle_stage: LifecycleStageSchema, created_at: Schema.Number, // Timestamp description: Schema.optional(Schema.String), + rivalry_override: Schema.optional(RivalrySchema), successor_ndo_hash: Schema.optional(Schema.Any), // ActionHash hibernation_origin: Schema.optional(LifecycleStageSchema), original_action_hash: Schema.optional(Schema.Any) diff --git a/ui/src/lib/services/zomes/governance.service.ts b/ui/src/lib/services/zomes/governance.service.ts index bfa19a7..fa6ada0 100644 --- a/ui/src/lib/services/zomes/governance.service.ts +++ b/ui/src/lib/services/zomes/governance.service.ts @@ -4,7 +4,18 @@ import { HolochainClientServiceTag, HolochainClientServiceLive } from '../holoch import { wrapZomeCallWithErrorFactory } from '$lib/utils/zome-helpers'; import { GovernanceError } from '$lib/errors/governance.errors'; import { GOVERNANCE_CONTEXTS } from '$lib/errors/error-contexts'; -import type { Commitment, EconomicEvent, VfEconomicEvent } from '@nondominium/shared-types'; +import type { + Commitment, + EconomicEvent, + VfEconomicEvent, + ProposeCommitmentInput, + ProposeCommitmentOutput, + LogEconomicEventInput, + LogEconomicEventOutput, + CheckActionConstraintsInput, + ConstraintViolation, + VfCommitment +} from '@nondominium/shared-types'; // ─── Service interface ──────────────────────────────────────────────────────── @@ -12,11 +23,20 @@ export interface GovernanceService { createCommitment: ( commitment: Omit ) => E.Effect; + /** Phase B: ValueFlows `propose_commitment` with `ndo_identity_hash`. */ + proposeCommitment: ( + input: ProposeCommitmentInput + ) => E.Effect; getCommitment: (hash: ActionHash) => E.Effect; + getAllCommitments: () => E.Effect; fulfillCommitment: (hash: ActionHash) => E.Effect; createEconomicEvent: ( event: Omit ) => E.Effect; + /** Phase B: ValueFlows `log_economic_event` with `ndo_identity_hash`. */ + logEconomicEvent: ( + input: LogEconomicEventInput + ) => E.Effect; getEconomicEvent: (hash: ActionHash) => E.Effect; getEventsByAgent: (agent: AgentPubKey) => E.Effect; getCommitmentsByProvider: (provider: AgentPubKey) => E.Effect; @@ -42,6 +62,9 @@ export interface GovernanceService { operation: string, agent: AgentPubKey ) => E.Effect; + checkActionConstraints: ( + input: CheckActionConstraintsInput + ) => E.Effect; createDispute: ( commitment: ActionHash, complainant: AgentPubKey, @@ -93,15 +116,32 @@ export const GovernanceServiceLive: Layer.Layer< createCommitment: (commitment) => wz('create_commitment', commitment, GOVERNANCE_CONTEXTS.CREATE_COMMITMENT), + proposeCommitment: (input) => + wz( + 'propose_commitment', + input, + GOVERNANCE_CONTEXTS.CREATE_COMMITMENT + ), + getCommitment: (hash) => wz('get_commitment', hash, GOVERNANCE_CONTEXTS.GET_COMMITMENT), + getAllCommitments: () => + wz('get_all_commitments', null, GOVERNANCE_CONTEXTS.GET_PENDING_COMMITMENTS), + fulfillCommitment: (hash) => wz('fulfill_commitment', hash, GOVERNANCE_CONTEXTS.FULFILL_COMMITMENT), createEconomicEvent: (event) => wz('create_economic_event', event, GOVERNANCE_CONTEXTS.CREATE_ECONOMIC_EVENT), + logEconomicEvent: (input) => + wz( + 'log_economic_event', + input, + GOVERNANCE_CONTEXTS.CREATE_ECONOMIC_EVENT + ), + getEconomicEvent: (hash) => wz('get_economic_event', hash, GOVERNANCE_CONTEXTS.GET_ECONOMIC_EVENT), @@ -171,6 +211,13 @@ export const GovernanceServiceLive: Layer.Layer< GOVERNANCE_CONTEXTS.VALIDATE_GOVERNANCE_RULES ), + checkActionConstraints: (input) => + wz( + 'check_action_constraints', + input, + GOVERNANCE_CONTEXTS.CHECK_ACTION_CONSTRAINTS + ), + createDispute: (commitment, complainant, description) => wz( 'create_dispute', diff --git a/ui/src/lib/services/zomes/ndo.service.ts b/ui/src/lib/services/zomes/ndo.service.ts index a23ff72..d5d8eb4 100644 --- a/ui/src/lib/services/zomes/ndo.service.ts +++ b/ui/src/lib/services/zomes/ndo.service.ts @@ -48,7 +48,8 @@ function ndoToDescriptorFields( successor_ndo_hash: entry.successor_ndo_hash ? encodeHashToBase64(entry.successor_ndo_hash) : null, - hibernation_origin: entry.hibernation_origin ? String(entry.hibernation_origin) : null + hibernation_origin: entry.hibernation_origin ? String(entry.hibernation_origin) : null, + rivalry_override: entry.rivalry_override ? String(entry.rivalry_override) : null }; } @@ -81,7 +82,8 @@ const mapListingToDescriptor = ( initiator: null, created_at: null, successor_ndo_hash: null, - hibernation_origin: null + hibernation_origin: null, + rivalry_override: null }; return { hash: encodeHashToBase64(listing.action_hash), diff --git a/ui/src/lib/services/zomes/resource.service.ts b/ui/src/lib/services/zomes/resource.service.ts index 3e5532c..03a1613 100644 --- a/ui/src/lib/services/zomes/resource.service.ts +++ b/ui/src/lib/services/zomes/resource.service.ts @@ -12,6 +12,8 @@ import type { EconomicResource, GetAllResourceSpecificationsOutput, ResourceSpecificationListing, + ResourceSpecificationInput, + CreateResourceSpecificationOutput, GetResourceSpecWithRulesOutput, GetAllNdosOutput, NdoInput, @@ -22,7 +24,10 @@ import type { LifecycleStage, ResourceNature, PropertyRegime, - OperationalState + OperationalState, + GovernanceRuleInput, + CheckRuleDataConstraintsInput, + ConstraintViolation } from '@nondominium/shared-types'; import type { Record as HoloRecord } from '@holochain/client'; import { @@ -30,14 +35,39 @@ import { type EconomicResourceRow } from '$lib/utils/holochain-records'; +function listingsFromOutput( + out: GetAllResourceSpecificationsOutput, + context: string +): E.Effect { + const { specifications, action_hashes } = out; + if (!action_hashes || action_hashes.length !== specifications.length) { + return E.fail( + ResourceError.create( + `${context}: action_hashes missing or length mismatch`, + context + ) + ); + } + const listings: ResourceSpecificationListing[] = specifications.map( + (specification: ResourceSpecification, i: number) => ({ + action_hash: action_hashes[i], + specification + }) + ); + return E.succeed(listings); +} + // ─── Service interface ──────────────────────────────────────────────────────── export interface ResourceService { createResourceSpecification: ( - spec: Omit - ) => E.Effect; + spec: ResourceSpecificationInput + ) => E.Effect; getResourceSpecification: (hash: ActionHash) => E.Effect; getAllResourceSpecifications: () => E.Effect; + getSpecificationsForNdo: ( + ndoHash: ActionHash + ) => E.Effect; getResourceSpecificationWithRules: ( specHash: ActionHash ) => E.Effect; @@ -83,6 +113,10 @@ export interface ResourceService { getResourcesByOperationalState: ( state: OperationalState ) => E.Effect; + createGovernanceRule: (input: GovernanceRuleInput) => E.Effect; + checkRuleDataConstraints: ( + input: CheckRuleDataConstraintsInput + ) => E.Effect; } // ─── Context Tag ───────────────────────────────────────────────────────────── @@ -119,7 +153,7 @@ export const ResourceServiceLive: Layer.Layer< return { createResourceSpecification: (spec) => - wz( + wz( 'create_resource_specification', spec, RESOURCE_CONTEXTS.CREATE_RESOURCE_SPECIFICATION @@ -138,24 +172,18 @@ export const ResourceServiceLive: Layer.Layer< null, RESOURCE_CONTEXTS.GET_ALL_RESOURCE_SPECIFICATIONS ).pipe( - E.flatMap((out) => { - const { specifications, action_hashes } = out; - if (!action_hashes || action_hashes.length !== specifications.length) { - return E.fail( - ResourceError.create( - 'get_all_resource_specifications: action_hashes missing or length mismatch', - RESOURCE_CONTEXTS.GET_ALL_RESOURCE_SPECIFICATIONS - ) - ); - } - const listings: ResourceSpecificationListing[] = specifications.map( - (specification: ResourceSpecification, i: number) => ({ - action_hash: action_hashes[i], - specification - }) - ); - return E.succeed(listings); - }) + E.flatMap((out) => + listingsFromOutput(out, RESOURCE_CONTEXTS.GET_ALL_RESOURCE_SPECIFICATIONS) + ) + ), + + getSpecificationsForNdo: (ndoHash) => + wz( + 'get_specifications_for_ndo', + ndoHash, + RESOURCE_CONTEXTS.GET_SPECIFICATIONS_FOR_NDO + ).pipe( + E.flatMap((out) => listingsFromOutput(out, RESOURCE_CONTEXTS.GET_SPECIFICATIONS_FOR_NDO)) ), getResourceSpecificationWithRules: (specHash) => @@ -297,7 +325,21 @@ export const ResourceServiceLive: Layer.Layer< 'get_resources_by_operational_state', state, RESOURCE_CONTEXTS.GET_RESOURCES_BY_OPERATIONAL_STATE - ).pipe(E.map(economicResourceRowsFromRecords)) + ).pipe(E.map(economicResourceRowsFromRecords)), + + createGovernanceRule: (input) => + wz( + 'create_governance_rule', + input, + RESOURCE_CONTEXTS.CREATE_GOVERNANCE_RULE + ), + + checkRuleDataConstraints: (input) => + wz( + 'check_rule_data_constraints', + input, + RESOURCE_CONTEXTS.CHECK_RULE_DATA_CONSTRAINTS + ) } satisfies ResourceService; }) ); diff --git a/ui/src/lib/stores/governance.store.svelte.ts b/ui/src/lib/stores/governance.store.svelte.ts index be3f6c6..e3e55bb 100644 --- a/ui/src/lib/stores/governance.store.svelte.ts +++ b/ui/src/lib/stores/governance.store.svelte.ts @@ -6,7 +6,17 @@ import { type GovernanceService } from '../services/zomes/governance.service.js'; import { withLoadingState, createLoadingStateSetter } from '$lib/utils/store-helpers/core'; -import type { Commitment, EconomicEvent } from '@nondominium/shared-types'; +import type { + Commitment, + EconomicEvent, + ProposeCommitmentInput, + ProposeCommitmentOutput, + LogEconomicEventInput, + LogEconomicEventOutput, + CheckActionConstraintsInput, + ConstraintViolation, + VfCommitment +} from '@nondominium/shared-types'; export interface ResourceFlow { events: EconomicEvent[]; @@ -34,11 +44,16 @@ export type GovernanceStore = { createCommitment: ( commitmentData: Omit ) => Promise; + proposeCommitment: ( + input: ProposeCommitmentInput + ) => Promise; fetchCommitment: (hash: ActionHash) => Promise; + fetchAllCommitments: () => Promise; fulfillCommitment: (hash: ActionHash) => Promise; createEconomicEvent: ( eventData: Omit ) => Promise; + logEconomicEvent: (input: LogEconomicEventInput) => Promise; fetchEconomicEvent: (hash: ActionHash) => Promise; fetchCommitmentsByProvider: (provider: AgentPubKey) => Promise; fetchCommitmentsByReceiver: (receiver: AgentPubKey) => Promise; @@ -65,6 +80,9 @@ export type GovernanceStore = { operation: string, agent: AgentPubKey ) => Promise; + checkActionConstraints: ( + input: CheckActionConstraintsInput + ) => Promise; createDispute: ( commitment: ActionHash, complainant: AgentPubKey, @@ -137,6 +155,17 @@ const createGovernanceStore = (): E.Effect { + return run(governanceService.proposeCommitment(input)); + } + + async function fetchAllCommitments(): Promise { + const exit = await E.runPromiseExit(governanceService.getAllCommitments()); + return Exit.isSuccess(exit) ? exit.value : []; + } + async function fetchCommitment(hash: ActionHash): Promise { const commitment = await run(governanceService.getCommitment(hash)); if (commitment) commitmentCache.set(hash.toString(), commitment); @@ -167,6 +196,19 @@ const createGovernanceStore = (): E.Effect { + return run(governanceService.logEconomicEvent(input)); + } + + async function checkActionConstraints( + input: CheckActionConstraintsInput + ): Promise { + const exit = await E.runPromiseExit(governanceService.checkActionConstraints(input)); + return Exit.isSuccess(exit) ? exit.value : []; + } + async function fetchEconomicEvent(hash: ActionHash): Promise { const event = await run(governanceService.getEconomicEvent(hash)); if (event) eventCache.set(hash.toString(), event); @@ -338,9 +380,12 @@ const createGovernanceStore = (): E.Effect; readonly allEconomicResources: EconomicResource[]; readonly myResources: EconomicResource[]; readonly selectedSpecification: ResourceSpecification | null; @@ -26,9 +32,10 @@ export type ResourceStore = { readonly resourcesByCustodian: Map; createResourceSpecification: ( - specData: Omit - ) => Promise; + specData: ResourceSpecificationInput + ) => Promise; fetchAllResourceSpecifications: () => Promise; + fetchSpecificationsForNdo: (ndoHash: ActionHash) => Promise; fetchResourceSpecification: (hash: ActionHash) => Promise; createEconomicResource: ( resourceData: Omit @@ -52,6 +59,10 @@ export type ResourceStore = { ) => Promise; deleteResourceSpecification: (hash: ActionHash) => Promise; archiveEconomicResource: (hash: ActionHash) => Promise; + createGovernanceRule: (input: GovernanceRuleInput) => Promise; + checkRuleDataConstraints: ( + input: CheckRuleDataConstraintsInput + ) => Promise; selectResourceSpecification: (specification: ResourceSpecification) => void; selectEconomicResource: (resource: EconomicResource) => void; clearSelections: () => void; @@ -70,6 +81,7 @@ const createResourceStore = (): E.Effect = $state(new Map()); // TODO: allEconomicResources is never populated — no store method writes to it. // Either wire fetchAllEconomicResources here or remove this getter from the public type before // connecting UI components so consumers are not misled by an always-empty array. @@ -97,11 +109,14 @@ const createResourceStore = (): E.Effect - ): Promise { - const hash = await run(resourceService.createResourceSpecification(specData)); - if (hash) await fetchAllResourceSpecifications(); - return hash; + specData: ResourceSpecificationInput + ): Promise { + const out = await run(resourceService.createResourceSpecification(specData)); + if (out) { + await fetchAllResourceSpecifications(); + await fetchSpecificationsForNdo(specData.ndo_identity_hash); + } + return out; } async function fetchAllResourceSpecifications(): Promise { @@ -119,6 +134,21 @@ const createResourceStore = (): E.Effect { + const listings = await run(resourceService.getSpecificationsForNdo(ndoHash)); + const key = ndoHash.toString(); + if (listings) { + specificationsByNdo.set(key, listings); + listings.forEach((listing) => { + specificationCache.set(listing.action_hash.toString(), listing.specification); + }); + return listings; + } + return specificationsByNdo.get(key) ?? []; + } + async function fetchResourceSpecification( hash: ActionHash ): Promise { @@ -220,6 +250,18 @@ const createResourceStore = (): E.Effect { + const record = await run(resourceService.createGovernanceRule(input)); + return record != null; + } + + async function checkRuleDataConstraints( + input: CheckRuleDataConstraintsInput + ): Promise { + const exit = await E.runPromiseExit(resourceService.checkRuleDataConstraints(input)); + return Exit.isSuccess(exit) ? exit.value : []; + } + function selectResourceSpecification(specification: ResourceSpecification) { selectedSpecification = specification; } @@ -233,6 +275,7 @@ const createResourceStore = (): E.Effect { export interface NdoFormInput { name: string; - regime?: 'Private' | 'Commons' | 'Nondominium' | 'CommonPool'; + regime?: + | 'Private' + | 'Commons' + | 'Collective' + | 'Pool' + | 'CommonPool' + | 'Public' + | 'Nondominium'; nature?: 'Physical' | 'Digital' | 'Service' | 'Hybrid' | 'Information'; stage?: string; description?: string; From 74532aa7a3cf84eb55a95c02e982ba24b26e23e3 Mon Sep 17 00:00:00 2001 From: Soushi888 Date: Thu, 13 Aug 2026 14:36:33 -0400 Subject: [PATCH 07/18] fix(e2e): tear down the clone-signing guard cell so the lobby stays empty The Phase 0 signing guard creates a `group` clone cell on agent 1 and never removes it. The UI enumerates group clone cells straight off `appInfo`, so the leftover cell rendered as a real group in the sidebar, `hasGroups` became true, and the next test's create-or-join onboarding CTA never mounted. Disable and delete the clone in a `finally` block, and expose `appId` on SeedClient for the admin-scoped delete. Pre-existing failure on `dev` (run 31285564294), not a Layer 1 regression. --- ui/tests/e2e/specs/core-flows.spec.ts | 28 ++++++++++++++++++++------- ui/tests/setup/harness.ts | 7 ++++++- 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/ui/tests/e2e/specs/core-flows.spec.ts b/ui/tests/e2e/specs/core-flows.spec.ts index 05031f2..c07e7d8 100644 --- a/ui/tests/e2e/specs/core-flows.spec.ts +++ b/ui/tests/e2e/specs/core-flows.spec.ts @@ -82,13 +82,27 @@ test.describe.serial('nondominium core flows', () => { modifiers: { network_seed: `e2e-clone-guard-${Date.now()}` } }); await authorizeWithRetry(seed.admin, clone.cell_id); - const myGroup = await seed.app.callZome({ - cell_id: clone.cell_id, - zome_name: 'zome_group', - fn_name: 'get_my_group', - payload: null - }); - expect(myGroup).toBeNull(); + try { + const myGroup = await seed.app.callZome({ + cell_id: clone.cell_id, + zome_name: 'zome_group', + fn_name: 'get_my_group', + payload: null + }); + expect(myGroup).toBeNull(); + } finally { + // The UI enumerates group clone cells straight off appInfo, so a leftover + // guard clone shows up in the sidebar as a real group and makes the next + // test's "empty lobby" precondition false. Tear it down here — the guard + // owns this cell, nothing downstream should see it. + await seed.app.disableCloneCell({ + clone_cell_id: { type: 'dna_hash', value: clone.cell_id[0] } + }); + await seed.admin.deleteCloneCell({ + app_id: seed.appId, + clone_cell_id: { type: 'dna_hash', value: clone.cell_id[0] } + }); + } }); // ── Phase 1: single-agent core flows ────────────────────────────────────── diff --git a/ui/tests/setup/harness.ts b/ui/tests/setup/harness.ts index 787cf26..9d81d81 100644 --- a/ui/tests/setup/harness.ts +++ b/ui/tests/setup/harness.ts @@ -123,6 +123,8 @@ export async function authorizeWithRetry( export interface SeedClient { app: AppWebsocket; admin: AdminWebsocket; + /** Installed app id — needed for admin calls scoped to the app (e.g. deleteCloneCell). */ + appId: string; close: () => Promise; } @@ -152,8 +154,10 @@ export async function createSeedClient(agent = 1): Promise { await authorizeWithRetry(admin, cellId); } + const appId = ready.appId || APP_ID; + const { token } = await admin.issueAppAuthenticationToken({ - installed_app_id: ready.appId || APP_ID, + installed_app_id: appId, single_use: false, expiry_seconds: 3600 }); @@ -168,6 +172,7 @@ export async function createSeedClient(agent = 1): Promise { return { app, admin, + appId, close: async () => { try { await app.client.close(); From 8e7f7d33d5470342ffc4448f1f4f0f837965203c Mon Sep 17 00:00:00 2001 From: Soushi888 Date: Thu, 13 Aug 2026 14:46:48 -0400 Subject: [PATCH 08/18] chore: drop the accidental empty Nondominium-game.dm file --- Nondominium-game.dm | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 Nondominium-game.dm diff --git a/Nondominium-game.dm b/Nondominium-game.dm deleted file mode 100644 index e69de29..0000000 From 09224eba30d7da663e4f9f35b85242fb99ea376b Mon Sep 17 00:00:00 2001 From: Soushi888 Date: Thu, 13 Aug 2026 15:30:43 -0400 Subject: [PATCH 09/18] test: bind GovernanceRule classification to Layer 0 and gate it in CI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Layer 1 constraint predicates were only ever exercised through `check_rule_data_constraints`, which takes the classification as a parameter. Nothing bound a rule's denormalized `property_regime` / `resource_nature` / `rivalry_override` to the NDO it claims to describe, so capture resistance was self-declared: an ownership-transfer rule on a Nondominium NDO passed simply by writing `Private` on the rule entry. Integrity now reads the referenced NondominiumIdentity and rejects any mismatch before evaluating constraints. All three fields are immutable on Layer 0, so the genesis record reached through the stable hash is authoritative and no update-chain walk is needed — the same read `validate_create_resource_spec` already performs. Four Sweettests cover the boundary: regime drift, nature drift, the misdeclared-regime bypass of REQ-RES-03, and a matching-classification guard so the binding cannot be over-tight. Verified red against the unfixed zome (3 failed / 2 passed) before the fix, green after (9/9). CI gains a `sweettest` job running the shared-crate unit tests and all five Sweettest targets, with `e2e` now gated behind it as the workflow comment asked. `--test-threads 2`: 6 threads with 11 conductor tests in flight gets SIGTERM'd. The empty-lobby e2e test asserts its precondition via `expectEmptyLobby` so a leaked group names itself instead of surfacing as "element not found". --- .github/workflows/build.yml | 52 ++++- dnas/nondominium/tests/src/resource/mod.rs | 200 ++++++++++++++++++ .../zomes/integrity/zome_resource/src/lib.rs | 43 ++++ ui/tests/e2e/specs/core-flows.spec.ts | 5 + ui/tests/e2e/utils/e2e-helpers.ts | 25 +++ 5 files changed, 321 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index da74ad6..f5d3d7f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -35,12 +35,56 @@ jobs: - name: Build happ run: nix develop --command bun run build:happ - # Browser-level e2e against real conductors (ui/tests/e2e). Gated behind the - # build job; when a Sweettest CI job lands, gate this behind that instead so - # backend regressions fail fast before the slower browser suite runs. - e2e: + # Primary backend suite (CLAUDE.md): pure predicate unit tests in + # crates/shared, then Sweettest against real conductors. Runs before e2e so a + # backend regression fails fast instead of surfacing as a confusing browser + # failure ten minutes later. + # + # --test-threads 2: each Sweettest spawns conductors, and 6 threads with 11 + # conductor tests in flight gets the runner OOM-killed (SIGTERM mid-suite). + sweettest: runs-on: ubuntu-latest needs: build + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + + - uses: cachix/install-nix-action@v26 + with: + github_access_token: ${{ secrets.GITHUB_TOKEN }} + + - uses: cachix/cachix-action@v14 + with: + name: holochain-ci + skipPush: true + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: | + . -> target + vendor/hrea -> vendor/hrea/target + + - name: Install dependencies + run: nix develop --command bun install + + # Sweettest loads the packaged .happ, so the WASM build is a prerequisite. + - name: Build happ + run: nix develop --command bun run build:happ + + - name: Run shared-crate unit tests + run: nix develop --command cargo test --package nondominium_shared + + - name: Run Sweettest suite + run: | + nix develop --command env CARGO_TARGET_DIR=target/native-tests \ + cargo test --package nondominium_sweettest -- --test-threads 2 + + # Browser-level e2e against real conductors (ui/tests/e2e). Gated behind + # sweettest so backend regressions fail before the slower browser suite runs. + e2e: + runs-on: ubuntu-latest + needs: sweettest steps: - uses: actions/checkout@v4 with: diff --git a/dnas/nondominium/tests/src/resource/mod.rs b/dnas/nondominium/tests/src/resource/mod.rs index 94dbc16..a512565 100644 --- a/dnas/nondominium/tests/src/resource/mod.rs +++ b/dnas/nondominium/tests/src/resource/mod.rs @@ -61,6 +61,11 @@ enum RuleDataMirror { max_quantity_per_period: Option, period_days: Option, }, + TransferCondition { + transfer_type: String, + requires_validation: bool, + validator_role: Option, + }, } #[derive(Debug, Serialize, Deserialize)] @@ -470,3 +475,198 @@ async fn check_rule_data_constraints_blocks_nondominium_ownership_transfer() { hard ); } + +// --------------------------------------------------------------------------- +// Layer 0 → Layer 1 trust boundary +// +// `check_rule_data_constraints` above proves the *predicate* works, but it +// takes the classification as a parameter — it says nothing about whether the +// integrity zome binds a rule's denormalized classification to the NDO it +// claims to describe. These tests cover that binding, which is what makes the +// Nondominium guarantees enforceable rather than self-declared. +// --------------------------------------------------------------------------- + +/// A rule whose denormalized `property_regime` contradicts its Layer 0 NDO is +/// rejected. Without this, every classification-driven constraint is advisory: +/// the writer picks the classification the validator will judge them against. +#[tokio::test(flavor = "multi_thread")] +async fn governance_rule_rejects_classification_drift_from_layer0() { + let (conductors, alice, _bob) = setup_two_agents().await; + + let ndo = create_ndo_at_stage( + &conductors, + &alice, + "Nondominium NDO for drift test", + "Active", + ) + .await; + + // create_ndo_at_stage pins property_regime to Commons; declare Private. + let result = conductors[0] + .call_fallible::<_, Record>( + &alice.zome("zome_resource"), + "create_governance_rule", + GovernanceRuleInput { + rule_data: RuleDataMirror::UsageLimit { + max_duration_hours: Some(4.0), + max_quantity_per_period: None, + period_days: None, + }, + enforced_by: None, + ndo_identity_hash: ndo, + property_regime: "Private".to_string(), + resource_nature: "Physical".to_string(), + rivalry_override: None, + specification_hash: None, + }, + ) + .await; + + assert!( + result.is_err(), + "a GovernanceRule declaring Private against a Commons NDO must be rejected; \ + otherwise the denormalized classification is attacker-controlled" + ); +} + +/// A rule whose denormalized `resource_nature` contradicts its Layer 0 NDO is +/// rejected. Nature drives rivalry defaults, so it is load-bearing too. +#[tokio::test(flavor = "multi_thread")] +async fn governance_rule_rejects_nature_drift_from_layer0() { + let (conductors, alice, _bob) = setup_two_agents().await; + + // create_ndo_at_stage pins resource_nature to Physical. + let ndo = create_ndo_at_stage(&conductors, &alice, "NDO for nature drift", "Active").await; + + let result = conductors[0] + .call_fallible::<_, Record>( + &alice.zome("zome_resource"), + "create_governance_rule", + GovernanceRuleInput { + rule_data: RuleDataMirror::UsageLimit { + max_duration_hours: Some(1.0), + max_quantity_per_period: None, + period_days: None, + }, + enforced_by: None, + ndo_identity_hash: ndo, + property_regime: "Commons".to_string(), + resource_nature: "Digital".to_string(), + rivalry_override: None, + specification_hash: None, + }, + ) + .await; + + assert!( + result.is_err(), + "a GovernanceRule declaring Digital against a Physical NDO must be rejected" + ); +} + +/// The capture-resistance gate holds against a misdeclared classification. +/// +/// This is the attack the drift binding exists to stop: an ownership-transfer +/// rule on a Nondominium NDO, smuggled past `check_rule_data_permitted` by +/// declaring `Private` on the rule entry. REQ-RES-03. +#[tokio::test(flavor = "multi_thread")] +async fn nondominium_ownership_transfer_not_bypassable_by_misdeclared_regime() { + let (conductors, alice, _bob) = setup_two_agents().await; + + let ndo: NdoOutput = conductors[0] + .call( + &alice.zome("zome_resource"), + "create_ndo", + NdoInput { + name: "Uncapturable NDO".to_string(), + property_regime: "Nondominium".to_string(), + resource_nature: "Physical".to_string(), + lifecycle_stage: "Active".to_string(), + description: None, + rivalry_override: None, + }, + ) + .await; + + let honest = conductors[0] + .call_fallible::<_, Record>( + &alice.zome("zome_resource"), + "create_governance_rule", + GovernanceRuleInput { + rule_data: RuleDataMirror::TransferCondition { + transfer_type: "Ownership".to_string(), + requires_validation: false, + validator_role: None, + }, + enforced_by: None, + ndo_identity_hash: ndo.action_hash.clone(), + property_regime: "Nondominium".to_string(), + resource_nature: "Physical".to_string(), + rivalry_override: None, + specification_hash: None, + }, + ) + .await; + + assert!( + honest.is_err(), + "ownership-transfer rule on a Nondominium NDO must be rejected (REQ-RES-03)" + ); + + let smuggled = conductors[0] + .call_fallible::<_, Record>( + &alice.zome("zome_resource"), + "create_governance_rule", + GovernanceRuleInput { + rule_data: RuleDataMirror::TransferCondition { + transfer_type: "Ownership".to_string(), + requires_validation: false, + validator_role: None, + }, + enforced_by: None, + ndo_identity_hash: ndo.action_hash, + // The bypass: claim a regime that permits ownership transfer. + property_regime: "Private".to_string(), + resource_nature: "Physical".to_string(), + rivalry_override: None, + specification_hash: None, + }, + ) + .await; + + assert!( + smuggled.is_err(), + "ownership-transfer rule on a Nondominium NDO must stay rejected even when \ + the rule entry declares Private — capture resistance cannot be self-declared" + ); +} + +/// An honest rule on a matching NDO still succeeds. Guards the drift binding +/// against being over-tight and breaking the happy path. +#[tokio::test(flavor = "multi_thread")] +async fn governance_rule_accepts_classification_matching_layer0() { + let (conductors, alice, _bob) = setup_two_agents().await; + + let ndo = create_ndo_at_stage(&conductors, &alice, "NDO for honest rule", "Active").await; + + let _: Record = conductors[0] + .call( + &alice.zome("zome_resource"), + "create_governance_rule", + GovernanceRuleInput { + rule_data: RuleDataMirror::UsageLimit { + max_duration_hours: Some(8.0), + max_quantity_per_period: None, + period_days: Some(7), + }, + enforced_by: None, + ndo_identity_hash: ndo, + // Matches create_ndo_at_stage: Commons / Physical. + property_regime: "Commons".to_string(), + resource_nature: "Physical".to_string(), + rivalry_override: None, + specification_hash: None, + }, + ) + .await; +} diff --git a/dnas/nondominium/zomes/integrity/zome_resource/src/lib.rs b/dnas/nondominium/zomes/integrity/zome_resource/src/lib.rs index 668656d..45dc061 100644 --- a/dnas/nondominium/zomes/integrity/zome_resource/src/lib.rs +++ b/dnas/nondominium/zomes/integrity/zome_resource/src/lib.rs @@ -373,6 +373,49 @@ fn validate_create_governance_rule( check_rule_data_permitted, hard_violation_message, has_hard_violation, ResourceClassification, }; + // Bind the denormalized classification to Layer 0 BEFORE judging the rule + // against it. Without this the classification is writer-controlled, and every + // regime-driven constraint (capture resistance above all) becomes advisory: + // an ownership-transfer rule on a Nondominium NDO passes simply by declaring + // `Private` on the rule entry. + // + // `property_regime`, `resource_nature`, and `rivalry_override` are immutable + // on NondominiumIdentity, so the genesis record reached through the stable + // Layer 0 hash is authoritative for all three — no update-chain walk needed, + // which is what makes this affordable inside integrity validation. + let ndo_record = must_get_valid_record(rule.ndo_identity_hash.clone())?; + let ndi: NondominiumIdentity = ndo_record + .entry() + .to_app_option() + .map_err(|e| { + wasm_error!(WasmErrorInner::Guest(format!( + "Failed to deserialize NondominiumIdentity referenced by GovernanceRule: {:?}", + e + ))) + })? + .ok_or(wasm_error!(WasmErrorInner::Guest( + "GovernanceRule.ndo_identity_hash does not reference a NondominiumIdentity".to_string() + )))?; + + if rule.property_regime != ndi.property_regime { + return Ok(ValidateCallbackResult::Invalid(format!( + "GovernanceRule declares property_regime {:?} but its NDO is {:?}", + rule.property_regime, ndi.property_regime + ))); + } + if rule.resource_nature != ndi.resource_nature { + return Ok(ValidateCallbackResult::Invalid(format!( + "GovernanceRule declares resource_nature {:?} but its NDO is {:?}", + rule.resource_nature, ndi.resource_nature + ))); + } + if rule.rivalry_override != ndi.rivalry_override { + return Ok(ValidateCallbackResult::Invalid(format!( + "GovernanceRule declares rivalry_override {:?} but its NDO is {:?}", + rule.rivalry_override, ndi.rivalry_override + ))); + } + let ctx = ResourceClassification { resource_nature: rule.resource_nature.clone(), property_regime: rule.property_regime.clone(), diff --git a/ui/tests/e2e/specs/core-flows.spec.ts b/ui/tests/e2e/specs/core-flows.spec.ts index c07e7d8..f3ea648 100644 --- a/ui/tests/e2e/specs/core-flows.spec.ts +++ b/ui/tests/e2e/specs/core-flows.spec.ts @@ -22,6 +22,7 @@ import { createGroup, createNdo, ensureLobbyProfile, + expectEmptyLobby, expectEventually, gotoAgent } from '../utils/e2e-helpers.js'; @@ -117,6 +118,10 @@ test.describe.serial('nondominium core flows', () => { }); test('empty lobby shows the create-or-join onboarding CTA', async () => { + // The CTA only renders when the agent has no groups, so the emptiness is a + // precondition rather than part of what is under test. Assert it first — + // when it breaks, the message should say so. + await expectEmptyLobby(page); await expect(page.getByText('Create or join a group to see NDOs')).toBeVisible(); }); diff --git a/ui/tests/e2e/utils/e2e-helpers.ts b/ui/tests/e2e/utils/e2e-helpers.ts index af8115b..187b48c 100644 --- a/ui/tests/e2e/utils/e2e-helpers.ts +++ b/ui/tests/e2e/utils/e2e-helpers.ts @@ -119,6 +119,31 @@ export async function saveGroupProfileIfPrompted(page: Page): Promise { } } +/** + * Asserts the agent has no groups yet. + * + * Several lobby behaviours (the create-or-join onboarding CTA above all) are + * only reachable from a genuinely empty lobby, and that emptiness is a property + * of shared conductor state rather than of the test itself. Any earlier test — + * or any spec file that happens to sort earlier, since the suite runs + * `workers: 1`, `fullyParallel: false` — can quietly invalidate it. + * + * Assert it explicitly so the failure names the broken precondition instead of + * surfacing ten seconds later as an inscrutable "element not found" on whatever + * the empty state was supposed to render. + */ +export async function expectEmptyLobby(page: Page): Promise { + const groupLinks = page.locator('nav a[href^="/group/"]'); + const count = await groupLinks.count(); + const names = count > 0 ? await groupLinks.allInnerTexts() : []; + expect( + count, + `precondition failed: expected an empty lobby, found ${count} group(s) in the sidebar ` + + `(${names.join(', ')}). Some earlier test leaked conductor state — check for a ` + + `clone cell or group that was created and never torn down.` + ).toBe(0); +} + /** * Creates a group through the sidebar and lands on /group/{seed}. Handles the * first-visit GroupProfileModal. From 923b3d8031ad19edd8317fac4aa5b8381d4a2b5f Mon Sep 17 00:00:00 2001 From: Soushi888 Date: Thu, 13 Aug 2026 16:52:43 -0400 Subject: [PATCH 10/18] fix(resource)!: gate Layer 1 on the observed NDO stage, shard sweettest in CI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Layer 1 lifecycle gate read `must_get_valid_record(ndo_identity_hash)`, which returns the *genesis* record. `lifecycle_stage` mutates through the update chain, so the gate judged every activation against the stage the NDO was created at: an NDO created at Ideation and advanced to Specification could never grow a spec, while one created at Active and since Deprecated still could. `ResourceSpecification` now carries `ndo_state_hash` — the NDO action the author observed — alongside the stable `ndo_identity_hash`. Integrity cannot walk an update chain forward (the set of updates grows, so validation would not replay), but backward is deterministic: every Update names exactly one predecessor via `original_action_address` and that edge never changes. `resolve_ndo_state` therefore reads the observed entry, walks back to the genesis Create, and proves the root matches `ndo_identity_hash` before gating on the stage. Capped at 64 hops; the chain is at most 10 stages in practice. The coordinator derives the field via `resolve_latest_ndo_record`, so honest clients are correct by construction, and `ndo_state_hash` is immutable on update so an edit cannot re-point a spec at a newer state to launder an activation the create-time gate rejected. Accepted limitation: an author writing directly to the DHT can present an old-but-eligible state. Two Sweettests cover both directions, verified red against the unfixed zome (0 passed / 2 failed) and green after (11/11). CI: the single sweettest job measured 61 min (run 31736241424) — 16 min compile plus 40 min of tests back-to-back. Sharded one job per target with a shared rust-cache key, and dropped the custom CARGO_TARGET_DIR: `target/native-tests` is right locally (keeps native artifacts away from the wasm build) but falls outside what rust-cache saves, so every run recompiled holochain test_utils. --- .github/workflows/build.yml | 35 +++++- dnas/nondominium/tests/src/resource/mod.rs | 82 ++++++++++++++ .../zome_resource/src/ndo_identity.rs | 2 +- .../src/resource_specification.rs | 17 +++ .../zomes/integrity/zome_resource/src/lib.rs | 104 +++++++++++++++--- 5 files changed, 223 insertions(+), 17 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f5d3d7f..63cd712 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -40,11 +40,36 @@ jobs: # backend regression fails fast instead of surfacing as a confusing browser # failure ten minutes later. # + # Sharded one job per [[test]] target. Measured on the first CI run of the + # whole suite in a single job (run 31736241424): 61 min total — 16 min of + # compile plus 40 min of tests executed back-to-back. Sharding overlaps the + # test time so wall clock tracks the slowest target rather than their sum: + # + # nondominium 16m · resource 13m · governance 6m · person 4m · misc 1.5m + # + # Two details make this work and are easy to undo by accident: + # + # * NO custom CARGO_TARGET_DIR. `CLAUDE.md` documents + # `CARGO_TARGET_DIR=target/native-tests` for local runs, which keeps the + # native test artifacts away from the wasm build. In CI that path falls + # outside what Swatinem/rust-cache saves, so every run recompiled + # holochain's test_utils from scratch — the 16 min. The default `target/` + # is cached, and cargo already separates wasm by target triple. + # * `shared-key` so all shards restore ONE cache rather than fighting over + # five. The first run on a new lockfile still pays the compile in + # parallel; later runs restore it. + # # --test-threads 2: each Sweettest spawns conductors, and 6 threads with 11 # conductor tests in flight gets the runner OOM-killed (SIGTERM mid-suite). sweettest: runs-on: ubuntu-latest needs: build + strategy: + # Report every failing target, not just the first — a shared regression + # usually breaks several, and seeing which ones is the diagnosis. + fail-fast: false + matrix: + target: [misc, person, governance, resource, nondominium] steps: - uses: actions/checkout@v4 with: @@ -61,6 +86,7 @@ jobs: - uses: Swatinem/rust-cache@v2 with: + shared-key: sweettest workspaces: | . -> target vendor/hrea -> vendor/hrea/target @@ -72,13 +98,16 @@ jobs: - name: Build happ run: nix develop --command bun run build:happ + # Pure predicate tests — no conductors, seconds to run. Only needs to run + # once, so it rides the cheapest shard. - name: Run shared-crate unit tests + if: matrix.target == 'misc' run: nix develop --command cargo test --package nondominium_shared - - name: Run Sweettest suite + - name: Run Sweettest target run: | - nix develop --command env CARGO_TARGET_DIR=target/native-tests \ - cargo test --package nondominium_sweettest -- --test-threads 2 + nix develop --command cargo test --package nondominium_sweettest \ + --test ${{ matrix.target }} -- --test-threads 2 # Browser-level e2e against real conductors (ui/tests/e2e). Gated behind # sweettest so backend regressions fail before the slower browser suite runs. diff --git a/dnas/nondominium/tests/src/resource/mod.rs b/dnas/nondominium/tests/src/resource/mod.rs index a512565..96d270b 100644 --- a/dnas/nondominium/tests/src/resource/mod.rs +++ b/dnas/nondominium/tests/src/resource/mod.rs @@ -670,3 +670,85 @@ async fn governance_rule_accepts_classification_matching_layer0() { ) .await; } + +// --------------------------------------------------------------------------- +// Layer 1 lifecycle gate — reads the NDO's *observed* state, not its genesis +// +// `lifecycle_stage` is mutable, so gating on the genesis record rejects the +// ordinary "create at Ideation, advance, then activate" flow and accepts an NDO +// that has since been deprecated. These tests pin the live behaviour. +// --------------------------------------------------------------------------- + +#[derive(Debug, Serialize, Deserialize)] +struct UpdateLifecycleStageInput { + pub original_action_hash: ActionHash, + pub new_stage: String, + pub successor_ndo_hash: Option, + pub transition_event_hash: Option, +} + +async fn advance_stage( + conductors: &SweetConductorBatch, + cell: &SweetCell, + ndo: &ActionHash, + new_stage: &str, + successor: Option, +) { + let _: ActionHash = conductors[0] + .call( + &cell.zome("zome_resource"), + "update_lifecycle_stage", + UpdateLifecycleStageInput { + original_action_hash: ndo.clone(), + new_stage: new_stage.to_string(), + successor_ndo_hash: successor, + transition_event_hash: None, + }, + ) + .await; +} + +/// The natural flow: an NDO starts at Ideation, advances, and only then grows a +/// Layer 1 specification. Gating on the genesis record would reject this even +/// though the NDO is eligible right now. +#[tokio::test(flavor = "multi_thread")] +async fn resource_spec_allowed_after_advancing_out_of_ideation() { + let (conductors, alice, _bob) = setup_two_agents().await; + + let ndo = create_ndo_at_stage(&conductors, &alice, "Advancing NDO", "Ideation").await; + advance_stage(&conductors, &alice, &ndo, "Specification", None).await; + + let _: CreateResourceSpecificationOutput = conductors[0] + .call( + &alice.zome("zome_resource"), + "create_resource_specification", + spec_input("Spec after advancing", "tools", ndo), + ) + .await; +} + +/// The mirror case: an NDO that has since been deprecated must not grow new +/// Layer 1 specs, even though it was created at an eligible stage. +#[tokio::test(flavor = "multi_thread")] +async fn resource_spec_rejected_after_deprecation() { + let (conductors, alice, _bob) = setup_two_agents().await; + + let successor = + create_ndo_at_stage(&conductors, &alice, "Successor NDO", "Active").await; + let ndo = create_ndo_at_stage(&conductors, &alice, "Doomed NDO", "Active").await; + advance_stage(&conductors, &alice, &ndo, "Deprecated", Some(successor)).await; + + let result = conductors[0] + .call_fallible::<_, CreateResourceSpecificationOutput>( + &alice.zome("zome_resource"), + "create_resource_specification", + spec_input("Spec on deprecated NDO", "tools", ndo), + ) + .await; + + assert!( + result.is_err(), + "activating Layer 1 on a Deprecated NDO must fail; gating on the genesis \ + record would wrongly allow it because the NDO was created at Active" + ); +} diff --git a/dnas/nondominium/zomes/coordinator/zome_resource/src/ndo_identity.rs b/dnas/nondominium/zomes/coordinator/zome_resource/src/ndo_identity.rs index 6499598..af95544 100644 --- a/dnas/nondominium/zomes/coordinator/zome_resource/src/ndo_identity.rs +++ b/dnas/nondominium/zomes/coordinator/zome_resource/src/ndo_identity.rs @@ -82,7 +82,7 @@ fn resolve_ndo_links(links: Vec) -> ExternResult> { /// Returns None if the original_action_hash does not exist on the DHT. /// /// Used by both get_ndo and update_lifecycle_stage to avoid duplicated chain traversal logic. -fn resolve_latest_ndo_record(original_action_hash: ActionHash) -> ExternResult> { +pub(crate) fn resolve_latest_ndo_record(original_action_hash: ActionHash) -> ExternResult> { let mut current_hash = original_action_hash; loop { match get_details(current_hash.clone(), GetOptions::default())? { diff --git a/dnas/nondominium/zomes/coordinator/zome_resource/src/resource_specification.rs b/dnas/nondominium/zomes/coordinator/zome_resource/src/resource_specification.rs index 8cf1761..3df2d51 100644 --- a/dnas/nondominium/zomes/coordinator/zome_resource/src/resource_specification.rs +++ b/dnas/nondominium/zomes/coordinator/zome_resource/src/resource_specification.rs @@ -89,6 +89,19 @@ pub fn create_resource_specification( )?; } + // Resolve the NDO's current state and record which action we observed, so + // integrity can gate on the live lifecycle stage rather than the + // creation-time one. Callers never supply this — deriving it here is what + // keeps honest clients correct by construction. + let ndo_state_hash = crate::ndo_identity::resolve_latest_ndo_record( + input.ndo_identity_hash.clone(), + )? + .ok_or(ResourceError::EntryOperationFailed( + "NondominiumIdentity not found for ndo_identity_hash".to_string(), + ))? + .action_address() + .clone(); + // Create the resource specification let spec = ResourceSpecification { name: input.name, @@ -99,6 +112,7 @@ pub fn create_resource_specification( is_active: true, // New specs are active by default scope: input.scope.clone(), ndo_identity_hash: input.ndo_identity_hash.clone(), + ndo_state_hash, }; let spec_hash = create_entry(&EntryTypes::ResourceSpecification(spec.clone()))?; @@ -298,6 +312,9 @@ pub fn update_resource_specification( is_active: true, scope: input.updated_specification.scope, ndo_identity_hash: original_spec.ndo_identity_hash, + // Carried over, not re-resolved: this records the state under which Layer 1 + // was *activated*, and editing a spec's name does not re-activate it. + ndo_state_hash: original_spec.ndo_state_hash, }; let updated_spec_hash = update_entry(input.previous_action_hash, &updated_spec)?; diff --git a/dnas/nondominium/zomes/integrity/zome_resource/src/lib.rs b/dnas/nondominium/zomes/integrity/zome_resource/src/lib.rs index 45dc061..8bfa86d 100644 --- a/dnas/nondominium/zomes/integrity/zome_resource/src/lib.rs +++ b/dnas/nondominium/zomes/integrity/zome_resource/src/lib.rs @@ -23,7 +23,18 @@ pub struct ResourceSpecification { /// DHT-anchor level until network-layer federation exists. pub scope: ResourceScope, /// Immutable pointer to the Layer 0 NondominiumIdentity this spec activates. + /// Always the *original* create_ndo action hash — the stable identity. pub ndo_identity_hash: ActionHash, + /// The NDO action the author observed when activating Layer 1. + /// + /// `lifecycle_stage` is mutable, and Holochain integrity cannot resolve "the + /// latest state" — walking an update chain *forward* is non-deterministic + /// because the chain keeps growing. Walking *backward* is deterministic, so + /// the author names the state they saw and validation proves that state + /// belongs to `ndo_identity_hash` before gating on its stage. + /// + /// Equal to `ndo_identity_hash` when the NDO has never been updated. + pub ndo_state_hash: ActionHash, } #[hdk_entry_helper] @@ -208,6 +219,14 @@ pub fn validate(op: Op) -> ExternResult { "ResourceSpecification ndo_identity_hash is immutable after creation".to_string(), )); } + // Also immutable: otherwise an edit could re-point the spec at a + // newer, eligible state and launder a Layer 1 activation that the + // create-time gate rejected. + if spec.ndo_state_hash != original.ndo_state_hash { + return Ok(ValidateCallbackResult::Invalid( + "ResourceSpecification ndo_state_hash is immutable after creation".to_string(), + )); + } validate_update_resource_spec(&spec, &action.author) } EntryTypes::EconomicResource(resource) => { @@ -287,6 +306,61 @@ pub fn validate(op: Op) -> ExternResult { } } +/// Longest NDO update chain integrity will walk. A NondominiumIdentity moves +/// through at most 10 lifecycle stages, so a legitimate chain is far shorter; +/// the cap only bounds work if a chain is ever driven pathologically long. +const MAX_NDO_CHAIN_WALK: usize = 64; + +/// Reads the NondominiumIdentity at `state_hash` and walks the update chain +/// *backward* to its genesis Create, returning `(root_action_hash, entry)`. +/// +/// Backward traversal is deterministic — every Update names exactly one +/// predecessor via `original_action_address`, and that edge never changes. +/// Forward traversal (`get_details(..).updates`) is not: the set grows as new +/// updates land, so validation that depended on it would not be replayable. +/// This is why the author supplies the state they observed rather than +/// validation resolving "latest" itself. +fn resolve_ndo_state( + state_hash: ActionHash, +) -> ExternResult<(ActionHash, NondominiumIdentity)> { + let record = must_get_valid_record(state_hash.clone())?; + let ndi: NondominiumIdentity = record + .entry() + .to_app_option() + .map_err(|e| { + wasm_error!(WasmErrorInner::Guest(format!( + "Failed to deserialize NondominiumIdentity at ndo_state_hash: {:?}", + e + ))) + })? + .ok_or(wasm_error!(WasmErrorInner::Guest( + "ndo_state_hash does not reference a NondominiumIdentity entry".to_string() + )))?; + + let mut current = record; + let mut current_hash = state_hash; + for _ in 0..MAX_NDO_CHAIN_WALK { + match current.action() { + Action::Create(_) => return Ok((current_hash, ndi)), + Action::Update(update) => { + current_hash = update.original_action_address.clone(); + current = must_get_valid_record(current_hash.clone())?; + } + other => { + return Err(wasm_error!(WasmErrorInner::Guest(format!( + "ndo_state_hash resolved to an unexpected action type: {:?}", + other.action_type() + )))) + } + } + } + + Err(wasm_error!(WasmErrorInner::Guest(format!( + "NondominiumIdentity update chain exceeded {} hops", + MAX_NDO_CHAIN_WALK + )))) +} + fn validate_create_resource_spec( spec: &ResourceSpecification, _author: &AgentPubKey, @@ -310,19 +384,23 @@ fn validate_create_resource_spec( } // Lifecycle gate: Layer 1 cannot activate while Layer 0 is Ideation / suspended / terminal. - let ndo_record = must_get_valid_record(spec.ndo_identity_hash.clone())?; - let ndi: NondominiumIdentity = ndo_record - .entry() - .to_app_option() - .map_err(|e| { - wasm_error!(WasmErrorInner::Guest(format!( - "Failed to deserialize linked NondominiumIdentity: {:?}", - e - ))) - })? - .ok_or(wasm_error!(WasmErrorInner::Guest( - "Linked NDO entry not found".to_string() - )))?; + // + // Read the stage from `ndo_state_hash` (the state the author observed), NOT + // from `ndo_identity_hash` — the latter is the genesis record and always + // carries the *creation-time* stage, so gating on it rejects the ordinary + // "create at Ideation, advance to Specification, then activate Layer 1" flow + // and accepts an NDO that has since been Deprecated. + let (root_hash, ndi) = resolve_ndo_state(spec.ndo_state_hash.clone())?; + + // The state must belong to the NDO the spec claims to activate. + if root_hash != spec.ndo_identity_hash { + return Ok(ValidateCallbackResult::Invalid( + "ResourceSpecification.ndo_state_hash belongs to a different NondominiumIdentity \ + than ndo_identity_hash" + .to_string(), + )); + } + let ineligible = matches!( ndi.lifecycle_stage, LifecycleStage::Ideation From b6691265f45251975e1e9e6a2497452f716e3ed1 Mon Sep 17 00:00:00 2001 From: Soushi888 Date: Sat, 15 Aug 2026 22:12:14 -0400 Subject: [PATCH 11/18] test(e2e): target the lifecycle stage field by test id, not by text Layer 1 activation puts the word "Specification" on the NDO detail page in more than one place: the identity panel's lifecycle stage, the Layer 1 specification panel, and its create modal. The multi-agent live-read test asserted `getByText('Specification', { exact: true })`, which became a Playwright strict-mode violation the moment Layer 1 rendered. Add `data-testid="ndo-lifecycle-stage"` to the stage field and assert on that. A structural selector would have worked too, but it would break again the next time the panel is restyled; the test id says what the test means. Local e2e: 19 passed, including the previously failing case. --- ui/src/lib/components/ndo/NdoView.svelte | 2 +- ui/tests/e2e/specs/multi-agent.spec.ts | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/ui/src/lib/components/ndo/NdoView.svelte b/ui/src/lib/components/ndo/NdoView.svelte index b992ee3..60f19a3 100644 --- a/ui/src/lib/components/ndo/NdoView.svelte +++ b/ui/src/lib/components/ndo/NdoView.svelte @@ -276,7 +276,7 @@

Lifecycle stage

-

+

{ndoDescriptor.lifecycle_stage ?? '—'}

diff --git a/ui/tests/e2e/specs/multi-agent.spec.ts b/ui/tests/e2e/specs/multi-agent.spec.ts index fd0c674..474af6a 100644 --- a/ui/tests/e2e/specs/multi-agent.spec.ts +++ b/ui/tests/e2e/specs/multi-agent.spec.ts @@ -164,7 +164,10 @@ test.describe.serial('nondominium multi-agent flows', () => { await expectEventually( bob, async () => { - await expect(bob.getByText('Specification', { exact: true })).toBeVisible({ + // Target the identity panel's stage field by test id, not by text: with + // Layer 1 activated, "Specification" also appears in the Layer 1 panel + // and its create modal, so a bare text match is a strict-mode violation. + await expect(bob.getByTestId('ndo-lifecycle-stage')).toHaveText('Specification', { timeout: 5_000 }); }, From b898f41e926705b72776aa0b96b5caf87841256f Mon Sep 17 00:00:00 2001 From: Soushi888 Date: Tue, 25 Aug 2026 19:11:05 -0400 Subject: [PATCH 12/18] fix(ui): route Layer 1 and Layer 2 calls to the NDO's own clone cell PR #128 moved every NDO into its own cloned `ndo` cell, but the Layer 1 and Layer 2 UI kept calling `zome_resource` and `zome_gouvernance` on the shared provisioned `nondominium` cell, where the NDO identity was never written. Creating a resource specification therefore failed with `Guest("Entry operation failed: Linked NondominiumIdentity not found")` from `resource_specification.rs:53`, and every NDO-scoped read returned nothing. `NdoService.resolveCellIdForNdo` resolves the NDO's clone cell from its anchor coordinates, provisioning it for a peer who never joined, and returns null for legacy NDOs still living in the shared cell so those keep working. `NdoView` resolves it once per NDO and passes `ndoCellId` to the resources, governance and activity tabs and to the four modals below them. An optional `cellId` threads through `zome-helpers` into both zome services and both stores; every call that does not pass one keeps its previous role-name routing. Two further defects surfaced while verifying this in the browser: - The governance tab's "+ New rule" handler carried a second, unrouted `fetchSpecificationsForNdo`. It returned nothing, so the rule was written with no `specification_hash` and no read path could surface it again. Routed, and guarded so the editor refuses to open when the NDO has no Layer 1 spec. - `anchorToDescriptor` omitted `rivalry_override`, leaving `bun run check` red on the branch. The anchor caches only the card fields, so it is null there and the live read on open supplies the real value. Verified in real Chrome against the 2-agent dev network: a specification and a typed AccessRequirement rule both create and read back. A probe through the app's own client confirms placement, `get_specifications_for_ndo` returning 0 for the shared cell, 0 for the provisioned `ndo` cell and 1 for the NDO's own clone. `bun run check` reports 0 errors and 0 warnings. --- ui/src/lib/components/ndo/ActivityTab.svelte | 23 +++- .../ndo/CommitmentCreateForm.svelte | 37 +++--- .../ndo/EconomicEventCreateForm.svelte | 49 ++++---- .../lib/components/ndo/GovernanceTab.svelte | 28 ++++- ui/src/lib/components/ndo/NdoView.svelte | 35 +++++- ui/src/lib/components/ndo/ResourcesTab.svelte | 18 ++- .../lib/components/ndo/RuleEditorModal.svelte | 41 ++++--- .../ndo/SpecificationCreateModal.svelte | 29 +++-- .../lib/services/zomes/governance.service.ts | 65 +++++++---- ui/src/lib/services/zomes/ndo.service.ts | 21 ++++ ui/src/lib/services/zomes/resource.service.ts | 105 ++++++++++++------ ui/src/lib/stores/governance.store.svelte.ts | 36 +++--- ui/src/lib/stores/resource.store.svelte.ts | 46 +++++--- ui/src/lib/utils/zome-helpers.ts | 13 ++- 14 files changed, 381 insertions(+), 165 deletions(-) diff --git a/ui/src/lib/components/ndo/ActivityTab.svelte b/ui/src/lib/components/ndo/ActivityTab.svelte index c218466..bd8f571 100644 --- a/ui/src/lib/components/ndo/ActivityTab.svelte +++ b/ui/src/lib/components/ndo/ActivityTab.svelte @@ -1,5 +1,5 @@ @@ -52,6 +61,7 @@ {#if showCreateModal} { showCreateModal = false; diff --git a/ui/src/lib/components/ndo/RuleEditorModal.svelte b/ui/src/lib/components/ndo/RuleEditorModal.svelte index 2ae05e2..eddcdf2 100644 --- a/ui/src/lib/components/ndo/RuleEditorModal.svelte +++ b/ui/src/lib/components/ndo/RuleEditorModal.svelte @@ -1,5 +1,5 @@