# PortaShape Product Canon — Single-File Edition

This file combines the canonical product documents for linear reading. Relative links may be easier to use from the multi-file edition.

---

<!-- BEGIN README.md -->

# PortaShape Product Canon

> **PortaShape makes digital systems visible, operable, and portable.**

PortaShape is a system-shaping workspace. It connects to the data, code, design, content, configuration, and live behavior of a digital product; turns that structure into an understandable control surface; and records the resulting relationships, transformations, policies, and operating knowledge as portable `.posh` artifacts.

Its public shorthand is:

> **See it. Shape it. Move it.**

This document set unifies the uploaded runtime-control concept, the mapping and migration concept, the `.posh` example catalog, and the Alpine.js + htmx documentation library under one product identity.

## The single purpose

PortaShape exists to let people **understand and deliberately change a digital system without losing the meaning, ownership, history, or portability of its values**.

That purpose includes work that previously looked like separate products:

- inspecting and editing data, configuration, styles, components, and runtime state;
- generating internal tools and control surfaces from existing systems;
- tuning design, motion, content, features, and application behavior live;
- mapping one system to another;
- translating values between formats and conventions;
- transmuting structures when one-to-one equivalents do not exist;
- snapshotting, comparing, migrating, synchronizing, validating, and reconstructing systems;
- saving reusable system knowledge as `.posh` files, libraries, policies, and workflows.

These capabilities belong together because they operate on the same underlying object: a **meaningful system value in context**. A value must first be discovered and understood before it can be exposed as a control, tuned, mapped, transformed, validated, moved, or preserved.

## The PortaShape loop

```text
CONNECT → DISCOVER → SURFACE → SHAPE → RELATE → SIMULATE → RUN → PRESERVE → LEARN
    ↑                                                                         ↓
    └──────────────────────────── continuous system loop ──────────────────────┘
```

This is one workspace with several lenses, not a website made of unrelated compartments.

- **Explore** reveals the system model and live state.
- **Shape** generates and composes controls for changing it.
- **Map** defines correspondence between systems.
- **Run** previews and executes transformations, migrations, and synchronization.
- **Compare** explains differences, provenance, validation, and drift.
- **Library** reuses adapters, controls, transformations, mappings, policies, and implementation patterns.

## Canonical product statement

**PortaShape is a system-shaping workspace that turns the hidden structure and live behavior of digital systems into controllable interfaces and reusable transformation models. It allows teams to inspect, tune, map, translate, validate, migrate, synchronize, and reconstruct systems while preserving meaning, authority, provenance, and user intent in portable `.posh` artifacts.**

## Product architecture at a glance

PortaShape is organized around a shared system graph and a set of cooperating engines:

1. **Connectors** read and write databases, APIs, files, codebases, design systems, content systems, and runtimes.
2. **Discovery** interprets schemas, values, relationships, constraints, events, and capabilities.
3. **System Model** stores the common graph used by every feature.
4. **Surface Engine** turns model elements into controls, views, dashboards, inspectors, and workflows.
5. **Runtime Bridge** observes and applies live changes.
6. **Relation Engine** defines mapping, translation, transmutation, synchronization, and dependency rules.
7. **Verification Engine** previews, simulates, validates, compares, and reports unresolved or lossy outcomes.
8. **Execution Engine** performs snapshots, patches, migrations, synchronization, and generated output.
9. **Provenance Engine** records source, transformation history, approval, compatibility, and audit evidence.
10. **Artifact and Library System** reads, writes, composes, versions, and shares `.posh` artifacts and reusable packages.
11. **Pattern Engine** learns recurring controls, mappings, workflows, and abstractions without hiding the resulting rules.

## Document map

| Document | Purpose |
| --- | --- |
| [`docs/01-purpose-and-positioning.md`](docs/01-purpose-and-positioning.md) | Product identity, promise, audience, and language. |
| [`docs/02-system-model-and-vocabulary.md`](docs/02-system-model-and-vocabulary.md) | The unified conceptual model and stable vocabulary. |
| [`docs/03-product-experience.md`](docs/03-product-experience.md) | One-workspace interaction model and user journeys. |
| [`docs/04-capabilities-and-modules.md`](docs/04-capabilities-and-modules.md) | Capability engines and how they cooperate. |
| [`docs/05-architecture.md`](docs/05-architecture.md) | Technical architecture, contracts, extensibility, and deployment. |
| [`docs/06-posh-artifact-model.md`](docs/06-posh-artifact-model.md) | The role and family of `.posh` artifacts. |
| [`docs/07-web-runtime-library.md`](docs/07-web-runtime-library.md) | Placement of the Alpine.js + htmx corpus inside PortaShape. |
| [`docs/08-use-cases-and-workflows.md`](docs/08-use-cases-and-workflows.md) | End-to-end workflows that use the complete product. |
| [`docs/09-governance-security-and-validation.md`](docs/09-governance-security-and-validation.md) | Safety, authority, permissions, validation, and audit. |
| [`docs/10-roadmap.md`](docs/10-roadmap.md) | Product sequence, MVP boundary, and ecosystem path. |
| [`docs/11-website-shape-translator-showcase-spec.md`](docs/11-website-shape-translator-showcase-spec.md) | Specification for the website-shape import, mapping, transmutation, save/manage, and export demo module. |
| [`docs/12-simple-shape-transmutation-examples.md`](docs/12-simple-shape-transmutation-examples.md) | Three dozen simple shape translation/transmutation playground examples for demos, tutorials, and UI smoke tests. |
| [`spec/PORTASHAPE_0.1_CONCEPTUAL_SCHEMA.md`](spec/PORTASHAPE_0.1_CONCEPTUAL_SCHEMA.md) | A coherent draft shape for the `.posh` standard. |
| [`SYNTHESIS_MAP.md`](SYNTHESIS_MAP.md) | Where each uploaded source was incorporated. |
| [`PORTASHAPE_PRODUCT_CANON.md`](PORTASHAPE_PRODUCT_CANON.md) | Single-file edition of the new canonical documents. |

## Included library and examples

The Alpine.js + htmx repository is preserved under [`libraries/web-native-runtime/reference/`](libraries/web-native-runtime/reference/) and repositioned as the **PortaShape Web-Native Runtime Library**. It is an implementation and education library for building generated control surfaces with explicit state ownership, DOM boundaries, semantic events, progressive enhancement, accessibility, and production discipline.

The examples catalog is available as MVP-ready machine-readable `.posh` playground fixtures under [`examples/`](examples/), including all three dozen simple shape translation and transmutation examples plus upgraded legacy catalog examples. A self-describing product bundle, [`examples/portashape-self-description.posh`](examples/portashape-self-description.posh), demonstrates how PortaShape can describe its own capabilities.

## Canon status

This package is a **product canon and conceptual specification**, not a claim that every described engine is already implemented. It provides the shared identity, architecture, vocabulary, file model, library placement, and delivery sequence needed to build the product as one coherent system.

<!-- END README.md -->

---

<!-- BEGIN docs/01-purpose-and-positioning.md -->

# PortaShape Purpose and Positioning

## Product identity

**Name:** PortaShape  
**Category:** System-shaping workspace  
**Tagline:** See it. Shape it. Move it.  
**Single purpose:** Make digital systems visible, operable, and portable.

The name PortaShape carries both sides of the product:

- **Porta** implies portability, transfer, gateways, connection, and passage between systems.
- **Shape** implies inspection, control, tuning, composition, transformation, and deliberate design.

PortaShape is therefore not merely an importer, dashboard builder, runtime inspector, or migration utility. It is the workspace in which a system becomes understandable enough to operate and structured enough to move.

## Canonical positioning statement

**PortaShape is a system-shaping workspace that connects to the materials and runtime behavior of a digital product, turns them into a live operational model, and lets teams inspect, control, map, transform, validate, and transfer that system through one family of interfaces. The complete explanation of the system and its changes can be preserved as portable `.posh` artifacts.**

## One-sentence descriptions by audience

### General

PortaShape lets you see how a digital system is put together, change it through generated controls, and move its meaning into another form.

### Product and operations teams

PortaShape generates the internal surfaces needed to inspect, operate, compare, and automate a product without requiring a separate bespoke tool for every workflow.

### Designers and motion practitioners

PortaShape turns production design tokens, components, brand rules, and motion parameters into live, testable controls that can be saved, compared, translated, and reused.

### Developers and architects

PortaShape builds a typed system graph from code, schemas, configuration, and runtime signals; projects that graph into control surfaces; and serializes mappings, transforms, policies, workflows, and provenance into `.posh` artifacts.

### Migration and integration teams

PortaShape makes source and destination systems inspectable in the same model, then maps, translates, transmutates, previews, validates, and records the transfer value for value wherever meaningful equivalence can be established.

## The problem PortaShape solves

Digital products are defined by many materials that rarely share one interface or vocabulary:

- databases, APIs, files, and application state;
- source code, schemas, routes, functions, events, and feature flags;
- CSS, design tokens, themes, component properties, and motion values;
- content models, assets, metadata, publishing rules, and localization;
- brand guidelines, policies, permissions, validation rules, and operational procedures;
- live runtime behavior, performance signals, jobs, and user interactions.

Each material often receives a separate panel, script, spreadsheet, editor, migration utility, dashboard, or body of documentation. The separation creates recurring costs:

- the same system is modeled repeatedly and inconsistently;
- operational interfaces drift from the source they represent;
- migration logic becomes disposable one-off code;
- design and runtime decisions lose provenance;
- users cannot tell whether a value is authoritative, derived, temporary, global, or personal;
- different roles work from incompatible representations of the same product;
- knowledge remains trapped in people, scripts, and documentation rather than becoming reusable system structure.

PortaShape solves these as one problem: **the system lacks a shared, operational representation of itself**.

## The unifying thesis

The runtime tuner and the mapping engine are not separate ideas. Both require the same facts:

- which values exist;
- what they mean;
- where they come from;
- who owns them;
- how they are typed and constrained;
- which values affect one another;
- how they may be changed;
- how they correspond to another context;
- how a change can be previewed, validated, traced, and saved.

Once PortaShape has this model, a control is simply one projection of a value, a mapping is one relationship between values, a migration is one execution of relationships, a snapshot is one serialized system state, and a generated tool is one composed view over the same graph.

## What PortaShape is

PortaShape is simultaneously:

- a **system discovery environment**;
- a **generated operational interface**;
- a **runtime tuning surface**;
- a **mapping and transformation workspace**;
- a **migration, synchronization, and reconstruction engine**;
- a **configuration snapshot and comparison system**;
- a **validation, policy, and provenance layer**;
- a **portable artifact language and reusable library ecosystem**.

These are expressions of one product purpose, not independent destinations.

## What PortaShape is not

PortaShape is not:

- a fixed dashboard with predetermined widgets;
- a no-code site builder disconnected from production systems;
- a client-side state store that replaces server authority;
- a black-box AI migration tool that cannot explain its output;
- a universal promise that every system can be converted without loss;
- a container that hides unrelated mini-apps behind one navigation bar;
- a requirement that every workflow use every PortaShape capability.

A user can begin with one control, one mapping, or one snapshot. The product remains coherent because every result participates in the same system model and artifact language.

## Core promise

PortaShape promises that a user can move from observation to action without changing conceptual tools:

1. connect to a real system;
2. discover its values and relationships;
3. inspect and control those values;
4. relate them to another system or desired state;
5. preview the consequences;
6. execute safely;
7. retain an inspectable explanation of what happened.

## Product principles

### Meaning before format

Preserve what a value means, not merely its current spelling or encoding.

### One model, many views

Inspectors, controls, maps, dashboards, comparisons, and reports are views over the same system graph.

### Connected to reality

Surfaces remain tied to actual data, code, configuration, and runtime behavior.

### Explicit authority

Every significant value and rendered boundary should have a declared authority and writer.

### Immediate feedback

Users should see the effect of a proposed or applied change as early as possible.

### Explicit loss and uncertainty

Unsupported, inferred, approximate, lossy, or unresolved outcomes must remain visible.

### Progressive complexity

A useful result should be possible from one connection or one drag-and-drop mapping, while experts can compose sophisticated transformations and workflows.

### Human-readable automation

Generated or AI-assisted logic should resolve into structured, reviewable rules wherever possible.

### Safe execution

Preview, permissions, validation, approvals, audit history, and rollback are foundational.

### Reuse by default

Controls, mappings, transforms, policies, workflows, adapters, and documentation should be composable and shareable.

## Naming guidance

Use **PortaShape** for the complete product and workspace.

Use capability names as verbs or engines within PortaShape rather than as standalone brands:

- PortaShape Connect
- PortaShape Explore
- PortaShape Shape
- PortaShape Map
- PortaShape Run
- PortaShape Compare
- PortaShape Library

Use **`.posh`** for the artifact format and **PortaShape Library** for reusable packages.

Use **PortaShape Web-Native Runtime Library** for the included Alpine.js + htmx implementation and teaching corpus.

Avoid calling the runtime interface “the other product.” It is PortaShape’s operational surface. Avoid calling mapping a separate app. It is PortaShape’s relation and transfer capability.

## Product shorthand

When a compact phrase is required, use one of these:

- **Make systems visible, operable, and portable.**
- **The workspace for seeing, shaping, and moving digital systems.**
- **The interface behind the interface—and the map between interfaces.**
- **From hidden system state to controllable, portable structure.**

<!-- END docs/01-purpose-and-positioning.md -->

---

<!-- BEGIN docs/02-system-model-and-vocabulary.md -->

# PortaShape System Model and Vocabulary

## Why a shared model is the product

PortaShape becomes coherent when every capability works from one representation of a digital system. Without that representation, control generation, runtime tuning, mapping, migration, validation, and documentation remain separate utilities. With it, they become different operations on the same graph.

The canonical PortaShape model is a **typed, semantic, provenance-aware graph of system elements and relationships**.

## Core objects

### System

A **system** is any bounded digital context PortaShape can inspect or affect. It may be a website, application, service, API, database, repository, design system, content platform, environment, user profile, workflow, brand system, animation engine, or composite of these.

A system declaration includes identity, adapter, environment, version, capabilities, permission scope, schema references, and connection metadata. Secrets are referenced, not embedded.

### Element

An **element** is anything meaningful within a system. Common element kinds include:

- value;
- object or record;
- schema or field;
- component or component property;
- design token or CSS declaration;
- route or content item;
- action or function;
- event or signal;
- asset;
- policy or validation rule;
- control or view;
- workflow or job;
- environment or deployment;
- user, role, or permission boundary.

### Value

A **value** is a typed piece of system state or configuration. It is the most common unit exposed, tuned, mapped, transformed, validated, and transferred.

A value should be describable by:

- stable identifier and path;
- human name and description;
- semantic role;
- data type and representation;
- current, default, proposed, and destination values where applicable;
- scope;
- authority owner;
- writer or mutation mechanism;
- lifecycle and persistence;
- constraints and allowed operations;
- sensitivity and permission requirements;
- provenance and observation time;
- confidence where discovered or inferred;
- control suggestions and display metadata.

### Relation

A **relation** is a typed edge between elements. Relation kinds include:

- contains;
- references;
- depends on;
- derives from;
- controls;
- renders;
- triggers;
- validates;
- conflicts with;
- maps to;
- translates to;
- transmutes into;
- synchronizes with;
- supersedes;
- was generated from.

Mappings are therefore not a separate data model. They are a specialized family of relations with execution semantics.

### Surface

A **surface** is an interactive projection of system elements. It may be a control panel, inspector, table, dashboard, editor, relationship map, component preview, timeline, workflow, or generated internal tool.

A surface does not own system truth simply because it displays or edits it. It declares which elements it projects, which operations it may request, and which runtime or authority will settle the result.

### Transform

A **transform** is a reusable operation that produces one representation or structure from another. It may be built in, declarative, formula-based, lookup-based, scripted, plugin-provided, externally executed, or AI-assisted.

Every transform should declare:

- accepted inputs and produced outputs;
- deterministic or probabilistic behavior;
- loss characteristics;
- reversibility;
- dependencies and runtime;
- permissions and trust level;
- validation and error behavior;
- version and provenance.

### Workflow

A **workflow** coordinates controls, relations, transformations, approvals, jobs, and execution steps toward a goal. A migration, design review, configuration promotion, customer onboarding, or incident diagnostic can all be workflows.

### Run

A **run** is an attempted execution of a snapshot, transformation, mapping, synchronization, workflow, or validation plan. It produces a durable report containing inputs, versions, decisions, outputs, warnings, errors, approvals, timing, and provenance.

### Artifact

An **artifact** is a portable `.posh` document. It can describe systems, surfaces, mappings, transforms, workflows, policies, snapshots, libraries, or runs. Artifacts can import and layer other artifacts.

### Library

A **library** is a reusable package of artifacts and implementation materials. It may contain adapters, schemas, controls, surfaces, mappings, transforms, policies, workflows, examples, documentation, or runtime code.

## System scopes

PortaShape uses explicit scopes to prevent unlike values from being confused.

### Settings

**Settings** are global, structural, environmental, or system-level choices. They define how a system operates and the boundaries within which users work.

Examples include API endpoints, supported themes, global typography, feature availability, rendering mode, security policy, migration behavior, and system-wide accessibility constraints.

### Options

**Options** are user-, account-, audience-, session-, or use-case-focused choices. They describe a selected experience within the boundaries established by settings.

Examples include preferred theme, visible columns, selected dashboard modules, saved filters, language preference, display density, and motion intensity.

### Runtime state

**Runtime state** is the observed or active condition of a system: current application state, events, jobs, request status, component behavior, performance values, or provisional values.

Runtime state may be transient, but it remains important for diagnosis, tuning, preview, and provenance.

### Content

**Content** is authored or managed information such as pages, records, assets, metadata, translations, and relationships.

### Derived values

**Derived values** are calculated, inferred, aggregated, or generated from other values. Their provenance must identify contributing sources and transforms.

### Secrets and references

Sensitive credentials and secrets are never treated as portable ordinary values. A `.posh` artifact references secure connection profiles, secret identifiers, or runtime bindings managed outside the artifact.

## Authority and writer contracts

The included web-runtime material contributes two foundational rules that PortaShape generalizes beyond Alpine.js and htmx.

### One authoritative owner per value

Copies, drafts, projections, caches, and previews may exist, but one declared authority settles the meaningful value.

Typical authorities include:

- server or database for durable, shared, permission-sensitive truth;
- URL or route for navigable state;
- native control for a submitted proposal;
- runtime subsystem for current execution facts;
- user profile for personal options;
- policy engine for constraints;
- source repository for code-owned configuration.

PortaShape stores authority as model metadata and uses it to determine which edits are temporary, proposed, committed, synchronized, or invalid.

### One intentional writer per rendered or mutable boundary

Every significant DOM region, file region, record field, configuration scope, or system boundary should have one intended mutation mechanism at a time.

PortaShape records the writer or execution path so that generated controls, transformations, and synchronization do not create competing mutation authorities.

### Semantic contracts across boundaries

Independent owners communicate through explicit operations and events. Command events request work; fact events announce completed outcomes. Payload, scope, timing, failure behavior, and version must be documented.

This rule applies to browser events, API messages, workflow steps, runtime signals, and system-to-system synchronization.

## Mapping vocabulary

### Mapping

Mapping establishes intended correspondence.

```text
source.siteTitle → destination.projectName
```

The names or structures may differ, but the relationship states that the values play equivalent or coordinated roles.

### Translation

Translation changes representation while preserving intended meaning.

Examples include unit conversion, enum lookup, date formatting, path rewriting, color conversion, identifier resolution, and token-to-variable conversion.

### Transmutation

Transmutation creates a destination form through substantial restructuring or derivation. It covers one-to-many, many-to-one, many-to-many, inferred, generated, or reconstructed outcomes.

Examples include generating a typography scale, reconstructing a component from content plus styles plus behavior, or deriving a destination theme from brand constraints.

### Synchronization

Synchronization repeatedly applies a relationship over time. Direction, trigger, reversibility, conflict policy, and loss behavior must be explicit.

## Relationship patterns

PortaShape supports:

- one-to-one;
- one-to-many;
- many-to-one;
- many-to-many;
- conditional;
- lookup;
- formula;
- template;
- procedural;
- semantic;
- event-triggered;
- bidirectional where safely reversible.

## Value lifecycle

A value may move through these states:

```text
DISCOVERED → CLASSIFIED → EXPOSED → PROPOSED → PREVIEWED → VALIDATED
          → APPROVED → APPLIED → OBSERVED → RECORDED → COMPARED
```

Not every workflow uses every state, but the distinctions prevent temporary tuning from being confused with production changes.

## Provenance model

For any result, PortaShape should answer:

- which source elements contributed;
- which relation and transform versions were used;
- what was copied, inferred, generated, or manually overridden;
- whether information was lost;
- which policy and validation checks ran;
- who or what approved the change;
- when and where it was applied;
- whether the destination has since drifted.

## Unresolved values

An unresolved value is a first-class model object, not an omission. It includes the source, reason, severity, candidate resolutions, required decision, fallback, and whether execution can continue.

## The system graph as shared language

Different roles may view the same element differently:

- a developer sees a property, schema, event, or function;
- a designer sees a token, component state, motion parameter, or visual role;
- an operator sees a field, queue, action, or status;
- a product manager sees a feature parameter, experiment, workflow, or outcome;
- a migration specialist sees source meaning, destination capability, and transfer risk.

PortaShape keeps these views connected by stable element identities and relations rather than creating independent copies of the system.

<!-- END docs/02-system-model-and-vocabulary.md -->

---

<!-- BEGIN docs/03-product-experience.md -->

# PortaShape Product Experience

## One workspace, several lenses

PortaShape should feel like one continuous environment, not a portal containing unrelated tools. The system model remains present while the user changes lenses according to the current task.

The workspace has six primary lenses:

1. **Explore** — inspect systems, schemas, values, relationships, runtime observations, and provenance.
2. **Shape** — generate, arrange, and use controls, views, dashboards, inspectors, and workflows.
3. **Map** — connect source and destination elements and define correspondence or transformation.
4. **Run** — preview, simulate, approve, execute, synchronize, and monitor work.
5. **Compare** — diff snapshots, environments, runs, mappings, values, behavior, and visual output.
6. **Library** — discover and compose adapters, controls, mappings, transforms, policies, surfaces, workflows, and documentation.

A lens changes emphasis, not identity. Selecting a value in Explore should select the same value in Shape, Map, Run, and Compare.

## The continuous task flow

### 1. Connect

The user connects one or more sources: an API, database, repository, file set, design system, runtime, website, or service.

PortaShape displays connection capabilities and permission boundaries before reading or writing.

### 2. Discover

The system detects or imports schemas, values, types, constraints, relationships, events, runtime signals, and known semantic roles.

Discovery results show confidence and evidence. Users may correct classifications, name concepts, or add annotations. Those decisions become reusable knowledge rather than remaining local UI labels.

### 3. Surface

PortaShape immediately projects useful elements into controls and views. Types, constraints, semantics, and permissions influence control selection.

Examples:

- a color becomes a color control and contrast preview;
- a bounded number becomes a slider or number field;
- an enum becomes a selector;
- a relationship becomes a linked view or graph;
- an event stream becomes a timeline;
- a schema becomes a data editor;
- an animation model becomes curves, timelines, and parameter controls;
- a component becomes an interactive preview with exposed properties.

### 4. Shape

The user adjusts values, composes higher-level controls, saves presets, groups recurring changes, and observes consequences.

The UI distinguishes:

- temporary override;
- proposed change;
- saved option;
- system setting change;
- source patch;
- destination write;
- generated output;
- production execution.

### 5. Relate

The user introduces another system, snapshot, or desired model and connects equivalent or dependent elements.

Mappings may be created by drag-and-drop, selection, search, keyboard actions, bulk operations, code, imported libraries, or suggestions. Suggestions show reasons and confidence.

### 6. Simulate

Before execution, PortaShape shows source, transformed, and destination values; affected elements; warnings; overwritten values; unsupported capabilities; policy results; loss; and unresolved decisions.

The user can interact with the preview using the same controls used for runtime shaping.

### 7. Run

The approved plan executes as a migration, patch, export, synchronization, reconstruction, configuration promotion, or workflow.

Progress is represented as system facts, not decorative loading state. Long-running work has explicit job identity, status, cancellation, retry, and result reports.

### 8. Preserve

The workspace saves the useful explanation as one or more `.posh` artifacts: system snapshot, surface, mapping, transform, workflow, policy, library, or run report.

### 9. Learn

PortaShape identifies repeated adjustments, unresolved patterns, frequently grouped controls, recurring mappings, validation failures, and domain concepts. It suggests reusable abstractions but keeps the generated rule inspectable.

## Workspace anatomy

A coherent default workspace can include:

### System rail

A compact inventory of connected systems, environments, snapshots, branches, and permission state.

### Model explorer

A searchable tree, table, graph, or schema view of elements and relationships.

### Primary canvas

The current composed surface: controls, mapping graph, comparison, dashboard, preview, or workflow.

### Inspector

Metadata, type, scope, authority, constraints, transforms, validation, and provenance for the selected object.

### Runtime and preview pane

Live rendering, system state, events, transformed output, or destination simulation.

### Run and evidence drawer

Planned operations, approvals, warnings, execution state, logs, validation, and resulting artifacts.

The workspace may be embedded, full-screen, sidecar, local development tool, hosted service, or generated project-specific application.

## Generated interface modes

### Automatic

Connect a system and receive a practical first surface based on types, semantics, permissions, and common patterns.

### Guided

Describe a goal such as “tune this component,” “manage customer accounts,” “compare themes,” “migrate this site,” or “monitor this process.” PortaShape composes the relevant system elements and controls.

### Manual

Experts place controls, views, queries, actions, relations, and workflow steps directly.

### Adaptive

The surface evolves with schema changes, runtime observations, saved preferences, usage patterns, and accepted suggestions.

## Interaction model

### Direct manipulation with an inspectable rule underneath

Drag-and-drop may create a mapping or group, but the result becomes a named, editable relation rather than an opaque line.

### Selection persists across lenses

A selected value remains the same object as the user moves from inspection to control to mapping to run evidence.

### Preview is operational

The preview is not only a screenshot. It can expose the transformed values, runtime state, component behavior, validation, and downstream effects that produce the rendered result.

### Controls can become structure

Repeated low-level changes can be promoted into presets, formulas, policies, workflows, or higher-level semantic controls.

### Documentation is attached to the model

Explanations, examples, onboarding material, and operating guidance link to the elements and workflows they describe. Documentation becomes part of the workspace rather than a separate static site.

## Role-sensitive views

PortaShape should adapt presentation and permission without forking the underlying model.

- Developers may prefer schemas, paths, code references, events, patches, and logs.
- Designers may prefer tokens, components, states, visual previews, constraints, and motion controls.
- Operators may prefer records, actions, queues, status, alerts, and playbooks.
- Product teams may prefer goals, experiments, cohorts, options, and outcomes.
- Administrators may prefer settings, permissions, policies, approvals, environments, and audit.

A shared model lets each role communicate through the same element identities and run history.

## Progressive complexity

The smallest successful PortaShape interaction can be:

- connect one source;
- expose one value;
- change it and see the result;
- save the control or snapshot.

The same system can grow into:

- multi-system semantic mapping;
- generated interfaces for multiple roles;
- layered organization and project libraries;
- approval workflows;
- ongoing synchronization;
- complete website reconstruction;
- reusable operational playbooks;
- AI-assisted pattern discovery with structured output.

## Experience rules

- Never hide whether a value is live, proposed, derived, or committed.
- Never imply complete equivalence when a transform is lossy or inferred.
- Never separate a generated control from its source and authority metadata.
- Never require users to rebuild the system model in each feature.
- Prefer visible relationships and narrow operations over global hidden state.
- Use ordinary web semantics, accessible controls, and direct URLs where they strengthen clarity and resilience.

<!-- END docs/03-product-experience.md -->

---

<!-- BEGIN docs/04-capabilities-and-modules.md -->

# PortaShape Capabilities and Modules

## Engines, not isolated mini-products

PortaShape contains several capability engines, but they should not appear as unrelated applications. Each engine reads and writes the same system graph, participates in the same provenance model, and produces composable `.posh` artifacts.

## 1. Connect

**Purpose:** Establish safe, typed access to systems.

**Capabilities:**

- databases, APIs, files, spreadsheets, event streams, repositories, runtimes, content systems, design systems, analytics, and services;
- read-only, write, environment, field, and role permissions;
- adapter discovery and capability negotiation;
- version, schema, and connection metadata;
- secure credential references;
- local, hosted, embedded, and agent-mediated connections.

**Produces:** system declarations, capability manifests, permission boundaries, connection diagnostics.

## 2. Discover

**Purpose:** Turn heterogeneous materials into a common system model.

**Capabilities:**

- schema and type discovery;
- code, configuration, route, component, event, token, and content interpretation;
- runtime observation;
- semantic role classification;
- constraint and validation extraction;
- ownership, lifecycle, and scope inference;
- dependency and relationship discovery;
- confidence and evidence recording;
- user annotations and corrections.

**Produces:** typed elements, relations, observations, suggested controls, suggested mappings.

## 3. Surface

**Purpose:** Generate useful interfaces from the system model.

**Capabilities:**

- type-to-control mapping;
- tables, filters, editors, inspectors, dashboards, graphs, timelines, previews, and workflow surfaces;
- automatic, guided, manual, and adaptive composition;
- permission-aware control generation;
- role-sensitive views over one model;
- accessible interaction patterns;
- reusable surface components and layouts;
- embedding into existing products or operating as a standalone workspace.

**Produces:** surface artifacts, saved views, control groups, role-specific compositions.

## 4. Runtime

**Purpose:** Observe and shape a connected system while it is operating.

**Capabilities:**

- live values, events, requests, jobs, component behavior, network activity, and performance signals;
- immediate temporary overrides;
- pause, replay, scenario simulation, and edge-case injection where supported;
- design-token and motion tuning;
- comparison of runtime configurations;
- promotion of accepted adjustments into source patches or configuration;
- capture of presets and runtime snapshots.

**Produces:** observations, proposed changes, presets, patches, snapshots, traces.

## 5. Relate

**Purpose:** Define how elements correspond within or across systems.

**Capabilities:**

- direct, one-to-many, many-to-one, many-to-many, conditional, lookup, formula, template, procedural, and semantic relations;
- drag-and-drop, keyboard, bulk, declarative, and suggested mapping;
- confidence and explanation;
- direction, priority, conflict, and synchronization policy;
- layered mappings from platform to organization to project to environment to user.

**Produces:** mapping and synchronization artifacts.

## 6. Transform

**Purpose:** Translate or transmute values and structures.

**Capabilities:**

- built-in conversions;
- visual formulas and lookup tables;
- template composition;
- scripts, plugins, external APIs, and sandboxed procedures;
- AI-assisted generation of structured transformations;
- code, token, asset, content, schema, and component generation;
- reversibility and loss analysis;
- reusable transform pipelines.

**Produces:** transform artifacts, generated values, conversion traces, loss metadata.

## 7. Verify

**Purpose:** Establish confidence before and after change.

**Capabilities:**

- type, range, format, schema, referential integrity, capability, permission, accessibility, brand, performance, and visual checks;
- assertions and policy evaluation;
- dry runs and simulation;
- unresolved value management;
- overwritten and downstream-effect analysis;
- source, transformed, and destination comparison;
- visual and behavioral regression support;
- compatibility and version checks.

**Produces:** validation reports, policy results, unresolved objects, risk summaries.

## 8. Run

**Purpose:** Execute controlled system change.

**Capabilities:**

- snapshots, patches, exports, imports, migrations, synchronization, reconstruction, generation, and workflow execution;
- one-time, manual, scheduled, event-driven, continuous, source-to-destination, destination-to-source, bidirectional, and preview-only modes;
- job state, retry, cancellation, idempotency, and partial rerun;
- approval gates and environment promotion;
- conflict-resolution strategies;
- rollback and compensation where supported.

**Produces:** run reports, changed systems, generated output, audit events, rollback points.

## 9. Compare

**Purpose:** Explain difference and drift.

**Capabilities:**

- snapshots across time;
- environments, branches, deployments, users, and systems;
- settings versus options;
- schema, token, component, content, route, permission, behavior, and runtime differences;
- mapping and transform version differences;
- migration inconsistency and destination drift;
- selective merge, transfer, approval, or rejection.

**Produces:** diffs, merge plans, drift alerts, updated mappings.

## 10. Preserve

**Purpose:** Retain reusable system knowledge.

**Capabilities:**

- `.posh` parsing, validation, writing, canonical formatting, and versioning;
- snapshots, surfaces, mappings, transforms, workflows, policies, libraries, and run reports;
- composition, imports, inheritance, overrides, namespaces, and signatures;
- human-readable notes and machine-readable semantics;
- source control integration and reviewable diffs.

**Produces:** portable artifacts and versioned system history.

## 11. Learn

**Purpose:** Convert repeated work into better abstractions.

**Capabilities:**

- identify frequently adjusted values;
- detect recurring mappings and transformation chains;
- recognize common unresolved destinations;
- suggest control groups, presets, workflows, policies, templates, and semantic concepts;
- analyze correlations, anomalies, and operational patterns;
- generate candidate rules with confidence and evidence;
- retain human acceptance or rejection as library knowledge.

**Produces:** suggestions, reusable abstractions, pattern reports, library contributions.

## 12. Library

**Purpose:** Share proven ways to connect, understand, control, and move systems.

A PortaShape library may include:

- adapters and connection profiles;
- schemas and semantic vocabularies;
- controls and surfaces;
- mapping packs;
- transformation functions;
- policies and validators;
- workflows and operational playbooks;
- implementation code;
- examples, tutorials, onboarding, and architecture guidance.

The included **PortaShape Web-Native Runtime Library** is the first example. It supplies patterns and education for building web control surfaces with server-rendered HTML, Alpine.js, htmx, native controls, semantic events, and explicit ownership boundaries.

## Cross-engine invariants

Every engine must preserve these invariants:

- stable element identity;
- explicit scope and authority;
- permission and sensitivity metadata;
- provenance and version context;
- visible uncertainty, loss, and unresolved state;
- artifact compatibility;
- common selection and inspection across lenses;
- safe separation between preview and execution.

<!-- END docs/04-capabilities-and-modules.md -->

---

<!-- BEGIN docs/05-architecture.md -->

# PortaShape Technical Architecture

## Architectural goal

The architecture must support one product loop across many system types without pretending they are identical. The stable center is a typed system graph plus explicit execution contracts. Adapters translate platform-specific behavior into that center; surfaces and workflows project the center for a particular task.

## Logical architecture

```text
┌──────────────────────────────── PORTASHAPE WORKSPACE ────────────────────────────────┐
│ Explore | Shape | Map | Run | Compare | Library                                     │
└───────────────────────────────┬───────────────────────────────────────────────────────┘
                                │ shared selections, commands, views
┌───────────────────────────────▼───────────────────────────────────────────────────────┐
│ Surface & Composition Engine | Runtime Bridge | Relation Editor | Run Console        │
└───────────────────────────────┬───────────────────────────────────────────────────────┘
                                │ typed operations
┌───────────────────────────────▼───────────────────────────────────────────────────────┐
│                 CANONICAL SYSTEM MODEL / GRAPH                                        │
│ elements | values | scopes | authority | relations | provenance | observations        │
└──────────────┬────────────────────┬────────────────────┬───────────────────────────────┘
               │                    │                    │
┌──────────────▼──────┐  ┌──────────▼──────────┐  ┌─────▼──────────────────────────────┐
│ Discovery &        │  │ Transform &          │  │ Policy, Validation & Provenance   │
│ Interpretation     │  │ Execution Runtime    │  │                                   │
└──────────────┬──────┘  └──────────┬──────────┘  └─────┬──────────────────────────────┘
               │                    │                    │
┌──────────────▼────────────────────▼────────────────────▼───────────────────────────────┐
│ Adapters: APIs | DBs | files | repos | design | content | runtime | services          │
└────────────────────────────────────────────────────────────────────────────────────────┘
                                │
┌───────────────────────────────▼───────────────────────────────────────────────────────┐
│ Artifact Store & Library Registry: `.posh`, packages, versions, signatures, reports    │
└────────────────────────────────────────────────────────────────────────────────────────┘
```

## Canonical system model

The system model is an addressable graph with typed nodes and edges. It should support:

- stable identities across snapshots and adapters;
- source-native paths alongside semantic identities;
- current, proposed, transformed, and destination values;
- schema and constraint references;
- settings, options, content, runtime, derived, and secret-reference scopes;
- authority owner and intended writer;
- capabilities such as read, propose, write, invoke, observe, subscribe, or generate;
- provenance, confidence, version, and observation timestamps;
- arbitrary extension namespaces without changing core semantics.

The graph can be backed by a document store, relational model, graph database, in-memory runtime, or combination. The API contract matters more than one storage technology.

## Adapter architecture

An adapter converts source-specific concepts into canonical model elements and operations.

An adapter may implement:

- connection and authentication;
- capability declaration;
- schema discovery;
- value reads and subscriptions;
- controlled writes or commands;
- validation delegation;
- event and job observation;
- source patch or export generation;
- stable identity strategy;
- version and compatibility reporting.

Adapters should be permission-minimal and may be read-only. A connector may expose only a subset of a system.

## Discovery and interpretation

Discovery combines:

- explicit schemas and metadata;
- static analysis;
- runtime observation;
- adapter-provided annotations;
- known semantic vocabularies;
- existing libraries and mapping history;
- user corrections;
- optional AI-assisted classification.

Every inferred fact carries confidence and evidence. Human correction becomes structured metadata that can be reused in later connections.

## Surface engine

The surface engine maps model elements to interactive components.

A control renderer considers:

- value type and representation;
- semantic role;
- constraints and allowed values;
- authority and write capability;
- scope and permissions;
- current and proposed values;
- validation and risk;
- preferred control from a library;
- target runtime and accessibility requirements.

Surface definitions should be declarative and portable. A renderer can target a hosted web UI, embedded panel, development overlay, generated application, desktop shell, or future client.

## Runtime bridge

The runtime bridge connects surface interaction to observed and applied system behavior.

It separates:

- **observation** — current facts from the system;
- **proposal** — a user or workflow’s intended value;
- **preview** — simulated result;
- **commit** — authoritative write or command;
- **settlement** — observed accepted outcome;
- **record** — provenance and run evidence.

This separation prevents a responsive UI from accidentally claiming authority it does not have.

## Relation and transformation engine

Relations form a graph that can be compiled into an execution plan.

The planner must account for:

- dependency order;
- transform input and output typing;
- conditions and lookups;
- defaults and fallbacks;
- direction and reversibility;
- conflicts and priority;
- capabilities and permissions;
- validation before and after stages;
- partial execution and resumability;
- deterministic versus probabilistic transforms;
- loss and unresolved values.

Transform runtimes may include built-in pure operations, sandboxed code, plugins, remote services, asset pipelines, or model-assisted procedures. Trust level and execution environment are explicit.

## Validation and policy architecture

Validation exists at several layers:

1. artifact schema validation;
2. adapter and connection validation;
3. source value validation;
4. transform input/output validation;
5. destination capability validation;
6. domain assertions and policies;
7. runtime or visual verification after execution.

Policies can gate preview, approval, execution, or promotion. Results are attached to elements, mappings, and runs.

## Provenance architecture

Provenance is append-oriented evidence, not an optional log string. A provenance record can link:

- source observations;
- artifact and library versions;
- relation and transform identifiers;
- user or agent decisions;
- approvals;
- execution environment;
- output values;
- validation results;
- later drift.

## Artifact store and library registry

The artifact subsystem provides:

- canonical JSON serialization;
- schema validation and migration;
- content-addressed identities or hashes;
- imports and dependency resolution;
- layered overrides;
- signatures and trust metadata;
- source-control-friendly formatting;
- package manifests;
- local, organization, and public registries;
- compatibility and deprecation information.

## Ownership contracts from the web runtime

The included Alpine.js + htmx material provides an implementation pattern for web surfaces:

- server/database own durable truth;
- URLs own navigable state;
- native controls hold submitted proposals;
- htmx owns requests and targeted server HTML installation;
- Alpine owns disposable local interaction;
- plain JavaScript islands own specialized browser behavior;
- semantic events coordinate boundaries;
- each significant DOM region has one intended writer.

PortaShape should encode these as surface and runtime metadata, not merely document them as developer advice.

## Web-native reference implementation

A practical initial renderer can use:

- server-rendered HTML for canonical projections;
- htmx for requests, targeted replacement, history, and multi-region updates;
- Alpine.js for immediate local state, focus, visibility, and disposable interaction;
- native forms and links for submitted and navigable state;
- semantic browser events for cross-boundary contracts;
- isolated JavaScript islands for complex editors, charts, canvases, or high-frequency interaction.

This architecture aligns with PortaShape’s emphasis on explicit authority, narrow mutation boundaries, progressive complexity, and inspectable operations.

## Extension model

Extension points include:

- adapters;
- semantic vocabularies;
- element kinds;
- control renderers;
- visualizations;
- transforms;
- validators and policies;
- workflow steps;
- exporters and generators;
- artifact namespaces;
- library packages.

Extensions declare compatibility, permissions, trust, and runtime requirements.

## Deployment models

PortaShape should support several deployments without changing the product model:

### Local development

A sidecar or overlay connected to a repository and local runtime.

### Embedded control surface

A PortaShape surface rendered inside an existing product with scoped permissions.

### Hosted workspace

A multi-system collaborative environment with libraries, approvals, runs, and history.

### Generated project tool

A standalone internal application generated from a surface and selected adapters.

### Agent-mediated operation

An agent may inspect, suggest, or execute through the same typed operations and policies as a human. Agent actions must retain identity, evidence, approvals, and limits.

## Non-functional requirements

- deterministic serialization where possible;
- accessible generated controls;
- incremental model loading for large systems;
- clear read/write boundaries;
- schema and adapter version compatibility;
- sandboxed untrusted transforms;
- resumable long-running jobs;
- inspectable event and operation traces;
- testable surface contracts;
- no raw secret requirement in portable artifacts.

<!-- END docs/05-architecture.md -->

---

<!-- BEGIN docs/06-posh-artifact-model.md -->

# The `.posh` Artifact Model

## Role of `.posh`

A `.posh` file is the durable language of PortaShape. The workspace is where a system is explored and changed; `.posh` is how the useful explanation of that work becomes portable, reviewable, reusable, and executable.

A `.posh` artifact can describe not only how one field maps to another, but also the systems involved, the controls used to operate them, the transforms and policies applied, the workflow that executed them, and the evidence produced.

## Design goals

The format should be:

- human-readable and machine-readable;
- JSON-based with canonical formatting;
- small for simple cases;
- composable for large systems;
- typed and versioned;
- inspectable and source-control-friendly;
- explicit about uncertainty, authority, loss, and unresolved values;
- extensible through namespaced additions;
- safe to share without embedding raw secrets.

## Artifact kinds

A `.posh` document declares a primary `kind`. Core kinds are:

### `system`

A system declaration or snapshot containing elements, values, relationships, settings, options, runtime observations, versions, and capabilities.

### `surface`

A generated or manually composed operational interface: controls, views, layout, queries, actions, permissions, and element bindings.

### `mapping`

Correspondence between source and destination elements, including direction, priority, conditions, transformations, fallbacks, and conflict rules.

### `transform`

Reusable conversion or generation logic with typed inputs, outputs, dependencies, trust, loss, and validation behavior.

### `workflow`

A sequence or graph of operations, approvals, jobs, retries, and results.

### `policy`

Validation, permission, safety, accessibility, brand, compatibility, or operational rules.

### `snapshot`

A point-in-time system state suitable for backup, comparison, migration, diagnostics, rollback, or environment reproduction.

### `run`

A durable execution report containing resolved inputs, versions, decisions, outputs, warnings, validation, approvals, and provenance.

### `library`

A package manifest for adapters, schemas, vocabularies, controls, surfaces, mappings, transforms, workflows, policies, examples, and documentation.

### `bundle`

A composed artifact that imports or embeds multiple kinds for a complete product, migration, project, or reusable capability.

## Conceptual root

```json
{
  "portaShape": {
    "formatVersion": "0.1",
    "kind": "bundle",
    "id": "example.bundle",
    "name": "Example Bundle",
    "description": "A composed system-shaping package.",
    "imports": [],
    "systems": [],
    "elements": [],
    "surfaces": [],
    "mappings": [],
    "transforms": [],
    "workflows": [],
    "policies": [],
    "settings": {},
    "options": {},
    "extensions": {},
    "metadata": {}
  }
}
```

Only fields relevant to the artifact kind need to be present.

## Systems and endpoints

A mapping or workflow can declare several systems rather than only one source and one destination. Each system includes:

- `id` and `type`;
- adapter and adapter version;
- environment;
- schema references;
- capabilities;
- credential or connection profile references;
- compatibility information;
- optional discovery snapshot.

Simple examples may retain `source` and `destination` aliases for readability.

## Element references

Element references can be:

- local IDs;
- source-native paths;
- semantic IDs;
- qualified references such as `systemId#elementId`;
- queries that resolve to sets of elements;
- imported library references.

Stable IDs should survive presentation changes and, where possible, schema evolution.

## Settings and options

The distinction between settings and options is first-class.

- `settings` represent global, structural, environmental, or system-level choices.
- `options` represent user-, account-, audience-, session-, or use-case-focused selections.

Artifacts may include mappings within each scope, but they must not silently collapse a personal option into a global setting or vice versa.

## Mapping records

A mapping record can declare:

- ID and human description;
- source and destination references;
- relation type;
- operation: copy, map, translate, transmute, synchronize, derive, generate, ignore, or unresolved;
- transform or transform pipeline;
- input and output types;
- conditions;
- defaults and fallbacks;
- lookup tables;
- direction and reversibility;
- loss characteristics;
- priority and dependency order;
- conflict policy;
- validation and assertions;
- confidence and explanation;
- approval status and notes.

## Transform records

Transforms should prefer structured forms such as:

- unit conversion;
- enum lookup;
- string template;
- formula;
- field combine or split;
- object reshape;
- path or URL rewrite;
- token conversion;
- schema projection;
- component generation;
- asset processing;
- sandboxed function;
- external service procedure;
- AI-assisted procedure with captured prompt, model/runtime metadata, constraints, and reviewed structured output.

## Surface records

A surface can describe:

- bound elements and queries;
- control types and renderer preferences;
- grouping, layout, and navigation;
- views, tables, previews, timelines, and graphs;
- actions and workflow triggers;
- role and permission rules;
- temporary, proposed, and committed states;
- event contracts and mutation boundaries;
- accessibility requirements;
- target renderer.

This allows a generated internal tool or runtime panel to be saved and reused just like a mapping.

## Workflow and execution

A workflow describes intended steps. A run records what actually happened.

A workflow step may:

- discover or refresh a system;
- request input;
- calculate or transform;
- validate;
- require approval;
- write or invoke;
- wait for a job or event;
- compare results;
- generate output;
- create a snapshot;
- publish a report;
- compensate or roll back.

Runs resolve imported versions and record exact inputs, outputs, environment, actor, timing, and results.

## Composition and layering

Libraries and projects can layer artifacts:

1. platform base;
2. organization standard;
3. project specialization;
4. environment override;
5. account or user options;
6. run-time proposal or temporary override.

Layer rules must identify whether a field replaces, merges, appends, removes, or conflicts. The resolved artifact should be inspectable before execution.

## Snapshots and comparison

A snapshot can capture:

- schemas and values;
- settings and options;
- design tokens and component defaults;
- routes, content, assets, and metadata;
- feature flags, permissions, and policies;
- animation parameters and runtime observations;
- adapter and system versions.

Comparisons produce added, removed, changed, retyped, drifted, unresolved, and incompatible results that can be promoted into a mapping or workflow.

## Provenance and traceability

Every generated destination value should be traceable to:

- source values;
- mapping and transform IDs;
- artifact and library versions;
- actor and approval;
- execution environment;
- validation outcomes;
- loss or inference;
- subsequent drift.

## Error and unresolved representation

Errors and unresolved values are explicit arrays or records, not discarded log text. They include severity, affected elements, reason, candidate resolution, fallback, continuation policy, and supporting context.

## Security and trust

A `.posh` file should:

- reference secrets rather than contain them;
- declare required capabilities;
- identify trusted and untrusted transforms;
- support signatures and integrity hashes;
- make external code or service execution visible;
- support environment and field restrictions;
- be safe to parse without executing procedures.

## Versioning

The format distinguishes:

- file format version;
- core schema version;
- extension versions;
- adapter versions;
- source and destination system versions;
- transform runtime versions;
- library package versions.

Compatibility should be checked before execution, and migrations between format versions should themselves be explicit and testable.

## Included examples

The `examples/` directory contains MVP-ready playground fixtures for the three dozen simple examples and upgraded legacy catalog examples. They cover copy, combine, split, translate, transmutate, flatten, componentize, tokenize, promote, extract, generate, verify, snapshot, and complete site transfer operations, plus a `portashape-self-description.posh` bundle. They remain conceptual and non-normative until the formal schema is implemented.

<!-- END docs/06-posh-artifact-model.md -->

---

<!-- BEGIN docs/07-web-runtime-library.md -->

# PortaShape Web-Native Runtime Library

## Placement within the product

The uploaded Alpine.js + htmx repository becomes the **PortaShape Web-Native Runtime Library**.

It is not a separate product and it is not the definition of PortaShape’s entire frontend. It is a reusable implementation, architecture, onboarding, and showcase library for one important target: web-native PortaShape control surfaces built from server-rendered HTML plus focused local interaction.

The source corpus is preserved under:

```text
libraries/web-native-runtime/reference/
```

A product-facing wrapper and pattern summary sit one level above the preserved source.

## Why this library belongs in PortaShape

The library’s central architecture mirrors PortaShape’s own conceptual requirements:

- one authoritative owner per state value;
- one intentional writer per DOM boundary;
- server authority for durable truth;
- URLs for navigable state;
- native controls for submitted values;
- htmx for HTTP interaction and targeted server HTML installation;
- Alpine.js for disposable browser-local interaction;
- semantic events for cross-boundary contracts;
- deliberate lifecycle, cleanup, security, accessibility, and production behavior.

PortaShape generalizes these from browser implementation advice into system-model metadata. The runtime library then demonstrates how those contracts can be rendered in a practical web stack.

## Product role

The library supports four PortaShape needs.

### 1. Reference renderer

It provides patterns for rendering generated surfaces with progressive enhancement, narrow server-updated regions, local interaction state, and accessible native controls.

### 2. Component contract library

Its stable-shell, replaceable-interior, disposable-component, event-handshake, and isolated-island patterns become reusable PortaShape surface primitives.

### 3. Contributor onboarding

Its twelve-day curriculum teaches the implementation discipline needed to build PortaShape panels and generated tools without creating duplicate state or competing DOM writers.

### 4. Showcase and pattern bank

Its example-page catalog supplies candidate demonstrations for forms, validation, search, lifecycle, events, multi-region updates, operations, and advanced composite workflows.

## Canonical PortaShape surface patterns

### Local control

Use a local reactive component when the value is immediate, disposable, and browser-local. The control may propose or preview a system value but does not silently become its authority.

### Server projection

Use a server-rendered fragment when the region is an authoritative representation of durable system state.

### Stable shell with live interior

Keep local chrome, focus, visibility, or workspace arrangement stable while refreshing a narrow server-owned projection inside it.

This pattern fits inspectors, drawers, modals, command palettes, detail panes, run consoles, and live dashboards.

### Replaceable component with disposable behavior

Replace the whole component when local interaction should intentionally reset after a server-settled operation.

This fits inline editors, rows, cards, submitted forms, and result states.

### Semantic event handshake

Use named domain events when one owner requests action from another or announces a completed fact. Event definitions should become part of the surface artifact and system model.

### Isolated JavaScript island

Use an explicit island for charts, mapping canvases, code editors, graph layout, drag systems, or high-frequency rendering. The island has clear initialization, cleanup, value bindings, and event contracts.

## Documentation structure

The preserved library includes:

- repository orientation and boot guidance;
- a master index;
- an extensive showcase idea bank;
- four companion architecture guides;
- a twelve-day onboarding curriculum;
- a single-file combined curriculum;
- a source reconciliation and claim audit;
- a machine-readable manifest.

The original relative layout is preserved so its internal links remain usable.

## Version and compatibility posture

The preserved material identifies its verified baseline as Alpine.js 3.15.12 and htmx 2.0.10 / stable 2.x on July 19, 2026, with htmx 4 treated as a version-gated prerelease line in that corpus.

Within PortaShape, the library manifest—not the product canon—owns these implementation version claims. Future revisions should update the library independently while preserving the product-level contracts.

## From training corpus to PortaShape library

The library should gradually gain PortaShape-native packages:

- control renderer definitions;
- surface pattern `.posh` files;
- event-contract schemas;
- accessible component templates;
- test matrices and validators;
- generated example applications;
- adapter examples for server frameworks;
- version compatibility metadata;
- mappings between model element types and web controls.

## What remains framework-neutral

PortaShape’s system model, `.posh` format, mapping engine, validation, provenance, and execution model must remain independent of Alpine.js and htmx. Other renderers can implement the same contracts with different technologies.

The web-native library is valuable because it demonstrates disciplined composition, not because PortaShape requires one frontend stack forever.

<!-- END docs/07-web-runtime-library.md -->

---

<!-- BEGIN docs/08-use-cases-and-workflows.md -->

# PortaShape Use Cases and End-to-End Workflows

## The value of unified workflows

A PortaShape use case should cross capabilities without feeling like a handoff between tools. The same selected values, controls, mappings, policies, and provenance follow the user from discovery through execution.

## 1. Runtime component tuning

**Goal:** Tune a production-connected component and preserve the result.

1. Connect the repository, token system, and development runtime.
2. Discover component properties, CSS variables, design tokens, events, and animation parameters.
3. Generate a component inspector and live preview.
4. Adjust spacing, color, typography, timing, easing, or feature flags.
5. Compare variants and capture a successful preset.
6. Validate accessibility, brand, performance, and allowed ranges.
7. Promote the preset into a source patch or configuration artifact.
8. Save the surface, preset, and provenance as `.posh` artifacts.

The same work can later become a reusable control for designers or an organization-wide component policy.

## 2. Website migration and reconstruction

**Goal:** Transfer a website value for value wherever meaningful equivalents exist.

1. Connect source and destination websites.
2. Discover content, schemas, routes, assets, styles, tokens, components, settings, options, permissions, interactions, and runtime behavior.
3. Generate source and destination explorers using the same vocabulary.
4. Accept or create mappings for equivalent elements.
5. Translate formats such as colors, units, paths, enums, content references, and dates.
6. Transmute structures where direct equivalents do not exist.
7. Preview destination rendering and behavior.
8. Expose unsupported, lossy, or unresolved values.
9. Run validation for routes, content completeness, accessibility, brand, behavior, permissions, and assets.
10. Execute in stages with approvals and rollback points.
11. Save mapping, run report, decisions, and destination snapshot.

The result is not only the migrated website. It is a portable, auditable explanation of the migration.

## 3. Design-system translation

**Goal:** Convert one token and component language into another.

1. Connect both token systems and component libraries.
2. Classify semantic roles rather than relying only on token names.
3. Surface colors, typography, spacing, radii, shadows, motion, and variants.
4. Map direct equivalents.
5. Generate or transform scales where structures differ.
6. Preview representative components using destination tokens.
7. validate contrast, consistency, allowed values, and unmapped roles.
8. Save a layered base mapping plus organization and product overrides.

## 4. Internal tool generation

**Goal:** Create an operational interface from an API or schema.

1. Connect an API, database, and permission model.
2. Discover records, fields, actions, relationships, constraints, and workflows.
3. Ask PortaShape to create a tool for a task such as customer support or content operations.
4. Review generated tables, forms, filters, actions, and status views.
5. Bind local presentation state and authoritative server operations using explicit ownership contracts.
6. Add role-specific options and system-wide settings.
7. Save the surface and workflow as a reusable project library.

## 5. Configuration snapshot, comparison, and promotion

**Goal:** Understand environment drift and safely promote selected changes.

1. Capture development, staging, and production snapshots.
2. Compare settings, options, feature flags, tokens, integrations, content configuration, and runtime deviations.
3. Classify intended differences versus drift.
4. Select changes to promote.
5. Preview destination impact and policy checks.
6. Require approval for high-risk settings.
7. execute a controlled promotion.
8. Record the run and create a new baseline snapshot.

## 6. Brand governance

**Goal:** Make brand guidance operational.

1. Connect brand documentation, token systems, components, content samples, and runtime pages.
2. Convert brand rules into semantic elements, constraints, examples, controls, and validators.
3. Generate a brand inspector for pages, components, motion, and content.
4. Detect deviations and show affected source elements.
5. Tune candidate corrections in preview.
6. Promote accepted fixes and store the policy library.

## 7. Content-system migration

**Goal:** Move content while preserving structure, relationships, routes, states, and editorial intent.

1. Discover content types, fields, references, assets, locales, states, routes, and permissions.
2. Map schemas and editorial concepts.
3. Translate dates, identifiers, rich text, paths, and status values.
4. Transmute incompatible block structures or generate missing destination fields.
5. Validate references, assets, routes, publishing state, and completeness.
6. Run incrementally and rerun changed items.
7. Retain per-item provenance and unresolved decisions.

## 8. Motion system laboratory

**Goal:** Tune and standardize animation across a product.

1. Connect the motion library and live components.
2. Expose duration, easing, spring, interpolation, trigger, and sequencing values.
3. Generate synchronized controls, curves, timelines, and previews.
4. Compare variations and record runtime performance.
5. Identify parameters repeatedly adjusted together.
6. Promote them into semantic motion presets and constraints.
7. Translate presets into another animation framework when needed.

## 9. AI and agent control surface

**Goal:** Make an AI system inspectable and governable.

1. Connect prompts, tools, routing, context sources, memory policies, evaluations, and runtime traces.
2. Model durable configuration separately from session options and live execution state.
3. Generate controls for safe parameters and read-only views for sensitive or authoritative data.
4. Compare runs and inspect provenance from input through tool calls to output.
5. Map configurations between model providers or agent runtimes.
6. Validate policy, privacy, cost, latency, and evaluation thresholds.
7. Save approved configurations and workflow definitions.

## 10. Web-native PortaShape surface development

**Goal:** Build a generated or hand-composed PortaShape interface using the included runtime library.

1. Declare state authority, submitted values, URL state, and DOM writers.
2. Use server-rendered HTML for authoritative projections.
3. Use htmx for narrow requests, swaps, history, and related multi-region updates.
4. Use Alpine.js for local focus, visibility, selection, and disposable previews.
5. Use semantic events as documented contracts.
6. Use native controls and progressive enhancement.
7. Test lifecycle, cleanup, races, errors, security, accessibility, and direct routes.
8. Package the resulting surface patterns and component contracts into a PortaShape library.

## 11. Customer onboarding and personalization portability

**Goal:** Import a customer’s data, organization settings, and user options into a product.

1. Connect the customer source and product destination.
2. Separate organization settings from individual user options.
3. Map records, roles, preferences, and content.
4. Validate permissions and scope boundaries.
5. Preview the customer-specific destination surface.
6. Execute with a run report and reusable customer-type mapping.

## 12. Operational pattern discovery

**Goal:** Turn repeated manual work into reusable capability.

1. Observe which values, filters, actions, and mappings are repeatedly used together.
2. Suggest a higher-level control, saved view, workflow, alert, or transform.
3. Show the supporting evidence and generated rule.
4. Let users accept, edit, reject, or scope the abstraction.
5. Save accepted patterns into a project or organization library.

## Common workflow invariant

Every use case follows the same PortaShape promise:

```text
real system → shared model → usable surface → deliberate relation or change
            → preview and validation → controlled execution → portable evidence
```

<!-- END docs/08-use-cases-and-workflows.md -->

---

<!-- BEGIN docs/09-governance-security-and-validation.md -->

# PortaShape Governance, Security, and Validation

## Governance is part of shaping

PortaShape may inspect and change production systems, generate code, move user data, alter global settings, execute transformations, and synchronize environments. Safety cannot be a final confirmation dialog attached to an otherwise opaque process. Authority, permission, validation, trust, and provenance belong in the system model from the beginning.

## Authority model

Every mutable element declares:

- the authoritative system or subsystem;
- allowed readers and writers;
- whether a surface can observe, propose, preview, commit, or invoke;
- environment restrictions;
- field or scope restrictions;
- whether approval is required;
- conflict and settlement behavior;
- audit sensitivity.

A responsive preview is not automatically authoritative. A disabled control is not authorization. An AI suggestion is not approval.

## Permission model

PortaShape should support:

- read-only connections;
- write and command permissions;
- field-level and element-level permissions;
- role and user restrictions;
- environment restrictions;
- separate permission for settings and options;
- approval workflows;
- temporary elevated access;
- scoped service identities;
- audit of human and agent actions.

Generated surfaces hide or disable unavailable operations, but enforcement remains at the adapter and authoritative system.

## Secret handling

Portable artifacts should not require raw secrets. They reference:

- connection profile IDs;
- environment bindings;
- secret-manager paths;
- credential capabilities;
- runtime-provided tokens.

Artifacts remain safe to inspect and version without executing or resolving secrets.

## Trust and execution

Transforms and extensions declare a trust class, for example:

- pure built-in operation;
- reviewed declarative transform;
- signed plugin;
- sandboxed user code;
- external service;
- AI-assisted procedure;
- untrusted imported logic.

The run planner can require stronger review, isolation, or deny execution based on trust, destination, and data sensitivity.

## Preview and dry run

Before material change, PortaShape should be able to present:

- original source value;
- proposed or transformed value;
- current destination value;
- overwritten values;
- dependent elements and downstream effects;
- settings and options changes;
- validation results;
- unresolved mappings;
- unsupported capabilities;
- generated values;
- loss and reversibility;
- required approvals;
- expected writes and commands.

A dry run produces a report that can be reviewed and signed without changing the destination.

## Validation layers

### Artifact validation

Check format version, required fields, references, typing, imports, extension schemas, signatures, and canonical serialization.

### Connection validation

Check adapter compatibility, permissions, environment, schema version, and required capabilities.

### Value validation

Check type, range, format, required fields, allowed values, and normalization.

### Relationship validation

Check mapping completeness, transform compatibility, dependency cycles, direction, reversibility, and conflict policy.

### Domain validation

Check referential integrity, asset existence, content completeness, route coverage, permission scope, brand rules, accessibility, performance, and business assertions.

### Post-execution validation

Observe destination state, behavior, visual output, jobs, and drift after the write settles.

## Assertions

Examples of portable assertions include:

- every published page has a title;
- every source route has a destination route;
- every source color role is mapped;
- no global setting is silently discarded;
- user options remain scoped to the correct user;
- destination motion remains within performance and accessibility limits;
- every generated value has provenance;
- no unapproved transform writes to production.

## Explicit loss

A transform declares whether it is:

- lossless and reversible;
- lossless but not automatically reversible;
- lossy with known discarded information;
- approximate;
- inferred with confidence;
- non-deterministic;
- unresolved.

The UI must never portray a lossy relation as safely bidirectional.

## Unresolved values

Unresolved values include:

- source element and value;
- intended destination context;
- reason;
- severity;
- candidate mappings or fallbacks;
- required human decision;
- continuation policy;
- effect on fidelity, functionality, accessibility, content, or security.

A run can pause, skip, use a fallback, or continue with explicit approval according to policy.

## Conflict handling

Synchronization and multi-writer workflows require a declared strategy:

- source wins;
- destination wins;
- most recent wins;
- priority system wins;
- merge;
- custom resolver;
- human approval.

PortaShape should show the authority assumptions and information loss of the chosen strategy.

## Audit and provenance

Audit records capture:

- actor identity, including agents and automation;
- operation and affected elements;
- source and destination systems;
- artifact, adapter, transform, and policy versions;
- approvals;
- before and after values where permitted;
- warnings, errors, and unresolved values;
- execution timing and environment;
- rollback or compensation action;
- later destination drift.

## Rollback and recovery

Rollback support may use:

- pre-run snapshots;
- inverse transforms where verified;
- source-control reversion;
- destination-native transactions;
- compensating workflows;
- item-level rerun;
- manual recovery instructions.

PortaShape must distinguish guaranteed rollback from best-effort compensation.

## Web surface safety

The Web-Native Runtime Library contributes implementation requirements for generated surfaces:

- server-side authentication, authorization, validation, CSRF enforcement, sanitization, transaction integrity, and audit;
- native accessible controls and labels;
- deliberate focus after swaps, errors, overlays, and navigation;
- semantic status announcements;
- strict boundaries for untrusted HTML;
- cleanup for timers, observers, listeners, and rich widgets;
- direct URL and normal form/link behavior where progressive enhancement is promised;
- version-aware htmx lifecycle and error handling;
- testing of full pages, fragments, races, history, accessibility, and lifecycle.

## AI governance

AI may assist with discovery, semantic classification, mapping suggestions, transform generation, documentation, and anomaly detection. PortaShape should record:

- model or service identity and version where available;
- input scope and protected data policy;
- prompt or procedure identity;
- confidence and evidence;
- generated structured rule;
- human review and modifications;
- deterministic validation applied afterward.

AI output should become inspectable PortaShape structure rather than an unexplained side effect.

<!-- END docs/09-governance-security-and-validation.md -->

---

<!-- BEGIN docs/10-roadmap.md -->

# PortaShape Product Roadmap

## Roadmap principle

Build the shared system model and one complete vertical workflow before expanding the number of connectors or isolated interface features. The product must prove that inspection, shaping, mapping, validation, execution, and artifact preservation are one loop.

## Phase 0 — Product canon and artifact foundations

**Outcome:** Stable vocabulary, repository structure, conceptual schema, and examples.

- adopt the single purpose and positioning;
- define system elements, scopes, authority, relations, surfaces, workflows, runs, and libraries;
- establish `.posh` artifact kinds and canonical JSON rules;
- extract and validate the example catalog;
- place the Alpine.js + htmx material as the Web-Native Runtime Library;
- define contribution, versioning, and compatibility conventions.

## Phase 1 — System model and inspector

**Outcome:** Connect one real system and make it understandable.

- implement adapter contract;
- support JSON/file and one API or runtime adapter;
- build typed element graph;
- display paths, types, values, constraints, scope, authority, and provenance;
- save and load a `system` or `snapshot` `.posh` artifact;
- support search, selection, and annotations.

**Proof:** A user can connect a system and produce a reusable, inspectable snapshot without hand-authoring its schema.

## Phase 2 — Generated control surface and runtime feedback

**Outcome:** Shape a connected system through generated controls.

- type-to-control rendering;
- temporary, proposed, and committed state distinctions;
- live observation and preview;
- surface composition and persistence;
- basic permissions and validation;
- initial web-native renderer using the runtime library patterns;
- source patch or configuration export for one supported target.

**Proof:** A user can expose a value, tune it, see the result, and save both the control surface and accepted output.

## Phase 3 — Mapping, transform, and simulation

**Outcome:** Relate two systems and preview a controlled transfer.

- source/destination explorer;
- direct, lookup, formula, combine, split, conditional, and template mappings;
- reusable transform registry;
- confidence-backed suggestions;
- dependency planning;
- unresolved values and explicit loss;
- dry-run report;
- mapping and transform artifact support.

**Proof:** A user can create a mapping through the UI, simulate it, inspect every produced value, and save a valid `.posh` file.

## Phase 4 — Execution, snapshots, and comparison

**Outcome:** Safely run and audit real changes.

- staged execution;
- run jobs and progress state;
- pre- and post-run snapshots;
- diff and drift views;
- approvals and environment policies;
- rerun and partial execution;
- rollback or compensation for supported adapters;
- signed run reports and provenance.

**Proof:** A user can migrate or promote a bounded system slice and explain exactly what changed and why.

## Phase 5 — Complete vertical product workflow

**Outcome:** Demonstrate the full PortaShape identity with one ambitious domain.

Recommended proving domain: **website system transfer and reconstruction** because it exercises content, styles, tokens, components, routes, assets, settings, options, permissions, runtime behavior, preview, validation, and migration.

Deliver:

- two supported website or content adapters;
- visual source/destination exploration;
- generated control surfaces;
- mapping and transmutation;
- destination preview;
- route, asset, content, visual, and accessibility validation;
- staged execution and run report;
- reusable mapping library.

## Phase 6 — Library ecosystem and collaboration

**Outcome:** Reuse becomes a first-class product advantage.

- package manifest and registry;
- organization, project, environment, and user layers;
- adapter and transform SDKs;
- policy and surface libraries;
- review, comments, approvals, and artifact diffs;
- compatibility and deprecation tooling;
- expanded Web-Native Runtime Library with PortaShape-native components and `.posh` patterns.

## Phase 7 — Pattern learning and assisted composition

**Outcome:** PortaShape helps users discover better abstractions.

- recurring control and mapping detection;
- suggested semantic concepts;
- workflow and policy suggestions;
- AI-assisted schema interpretation and transform drafting;
- evidence, confidence, review, and structured acceptance;
- cross-project knowledge with privacy and organization boundaries.

## MVP boundary

The first coherent MVP should include:

- two simple adapters;
- one system explorer;
- generated controls for common types;
- live preview for one target;
- source/destination mapping;
- a small transform library;
- simulation and validation;
- `.posh` save/load;
- provenance for every output;
- one runnable end-to-end migration or configuration-promotion workflow.

Do not call a set of disconnected inspector, dashboard, and mapper demos an MVP. The proof is continuity across the loop.

## Intentionally deferred

Until the core loop is proven, defer:

- broad connector marketplaces;
- fully autonomous migration;
- universal bidirectional synchronization;
- a large visual app-builder feature set;
- many frontend renderer technologies;
- high-frequency collaborative canvas editing;
- unsupported claims of full website fidelity;
- opaque AI transformations;
- public artifact registry without trust and compatibility controls.

## Product health measures

Useful measures include:

- time from connection to first useful surface;
- percentage of discovered values with type, scope, authority, and provenance;
- mapping suggestion acceptance and correction rates;
- unresolved and silently discarded value counts;
- preview-to-successful-run conversion;
- validation failures caught before execution;
- reuse rate of mappings, transforms, surfaces, and policies;
- ability to reproduce a run from artifacts and versions;
- destination drift detected after execution;
- number of repeated manual actions promoted into reusable abstractions.

## Definition of product coherence

PortaShape is coherent when:

- a value has one identity across inspection, control, mapping, execution, and comparison;
- every change can reveal authority, constraints, provenance, and effect;
- every useful operation can be preserved as an artifact or library contribution;
- a simple control and a complete migration use the same conceptual primitives;
- implementation libraries fit under the product model rather than defining separate products.

<!-- END docs/10-roadmap.md -->

---

<!-- BEGIN docs/11-website-shape-translator-showcase-spec.md -->

# Website Shape Translator Showcase Specification

## Purpose

This specification defines the demonstration website for PortaShape's flagship capability: importing a shape, exposing the labeled values that make it up, letting a user translate or transmutate those values into a new shape, and saving the result as reusable `.posh` artifacts.

The demo uses a website because it is an immediately understandable shape. A user uploads `index.htm`, `styles.css`, and `scripts.js`; PortaShape discovers the page structure, labels, IDs, styles, scripts, assets, interactions, and reusable sections; then the user can tweak values, save the current website shape, transmutate the whole site into a new shape, or select one element such as a single `div` and turn it into a reusable component shape.

## Product framing

The website system is not a separate website builder. It is the first showcase module for PortaShape's general shape translation engine.

A **shape** is anything that has labeled things compounded into a singular labeled thing with a stable unique ID. In this module, a website shape may contain pages, sections, components, DOM nodes, text values, design tokens, assets, routes, event handlers, forms, animations, layout rules, and runtime behaviors. A selected `div` can also become a shape when PortaShape assigns or preserves a stable shape ID and records the labeled sub-values that compose it.

A **registered shape ID** allows a user or workflow to import data into that shape, export data from that shape, compare it to another shape, or translate it through a transmutation pipeline into a destination shape.

**Transmutation** is the act of changing the source shape's structure, values, semantics, or representation so it can become another shape. **Translation** is the whole movement from source shape through discovery, mapping, transmutation, verification, and destination save/export.

## Core user promise

> Upload a website, see its shape, change or transmutate it, and save the new shape so it can be reused, exported, or translated again.

## Demonstration goals

The demo must show that PortaShape can:

1. import common website files as a meaningful shape;
2. discover and label editable variables across HTML, CSS, and JavaScript;
3. register, save, load, duplicate, version, and manage website and component shape IDs;
4. present a visual data mapper over source and destination shapes;
5. support small tweaks such as changing one or two values;
6. support larger transmutations such as changing a one-page marketing site into a dashboard, landing page variant, reusable card component, or differently configured website;
7. let the user select a single DOM subtree and save it as an instantly reusable shape;
8. preview changes before committing them;
9. explain what was copied, translated, transmutated, ignored, lossy, or unresolved;
10. export the destination as website files and `.posh` artifacts.

## Inputs and upload contract

### Required upload set

The first demo version accepts exactly these files:

- `index.htm` or `index.html` — canonical page markup;
- `styles.css` — style rules, design values, layout, typography, colors, and motion definitions;
- `scripts.js` — client-side behavior, event listeners, configuration values, constants, and lightweight interactions.

### Optional later inputs

Future iterations may accept assets, fonts, images, JSON data, multiple pages, framework projects, CMS exports, design-token files, screenshots, accessibility reports, or live URLs. These should be modeled as additional adapters, not as a separate product path.

### Upload validation

The upload surface must validate:

- expected filenames and MIME/file extensions;
- maximum file size and total package size;
- parseability of HTML and CSS;
- JavaScript syntax and safe static-analysis boundaries;
- rejected executable upload behavior for the hosted demo;
- duplicate IDs and malformed DOM roots;
- missing style/script references;
- encoding and line-ending normalization.

Invalid files must produce clear validation results and preserve the user's ability to retry without losing accepted files.

## Shape discovery model

After upload, PortaShape creates a source shape record with a new stable shape ID unless the upload includes an existing `.posh` shape declaration.

Discovery should identify:

### HTML elements

- document title, meta values, landmarks, headings, sections, forms, buttons, links, images, lists, cards, tables, dialogs, and custom attributes;
- DOM paths and stable identities using existing `id`, `name`, semantic role, text signature, source location, and generated fallback IDs;
- repeated structures that may become component shapes;
- labels, accessible names, ARIA relationships, form-control associations, and successful controls;
- reusable subtrees such as `header`, `nav`, `main`, `section`, `article`, `footer`, and user-selected `div` regions.

### CSS values

- colors, fonts, spacing, sizing, border radii, shadows, breakpoints, z-index layers, animation durations/easing, grid/flex layout patterns, and CSS custom properties;
- inferred design tokens where raw values repeat or match semantic roles;
- selectors that bind style values to discovered HTML elements;
- global settings versus local component options.

### JavaScript values and behavior

- constants, configuration objects, data literals, selectors, event listeners, DOM writes, class toggles, inline state machines, fetch calls, timers, and browser API usage;
- behavior labels such as menu toggle, carousel, modal open/close, form enhancement, active search, animation trigger, or analytics event;
- ownership boundaries where plain JavaScript islands are required;
- values that can safely become controls versus behavior that must remain read-only in the demo.

### Shape variables

The UI must list discovered variables in groups:

- **Content variables** — title text, headings, paragraphs, labels, alt text, links, button copy, metadata;
- **Design variables** — color tokens, typography, spacing, layout, radii, shadows, responsive settings;
- **Structure variables** — sections, repeated cards, navigation items, forms, component boundaries;
- **Behavior variables** — toggles, event handlers, animation timings, script constants, data attributes;
- **Asset variables** — image paths, icon references, font references, downloadable files;
- **Runtime variables** — request endpoints, local UI state, browser API integrations, feature flags where detectable;
- **Policy variables** — accessibility requirements, allowed value ranges, brand constraints, security constraints.

Each variable row must show label, stable element ID, source file and location, inferred type, current value, owner/scope, confidence, editability, dependencies, and provenance evidence.

## Shape registry and dashboard

The demo needs a shape load/save/manage dashboard. It must include:

- registered shape IDs and human-readable labels;
- shape kind, such as `website`, `page`, `section`, `component`, `token-set`, `interaction`, `workflow`, or `bundle`;
- import/export capability status;
- source upload timestamp and version;
- saved variants and lineage;
- current draft versus committed versions;
- compatibility notes for translation targets;
- unresolved or lossy transformation warnings;
- quick actions: open explorer, duplicate, save as new shape, export files, export `.posh`, compare, delete local draft.

The dashboard should make the source shape, proposed shape, and destination shape visually distinct.

## Primary screens

### 1. Upload and connect screen

Purpose: import the website files and create a source shape.

Required UI:

- drag-and-drop upload zone with separate slots for `index.htm`, `styles.css`, and `scripts.js`;
- parse status for each file;
- detected references among the files;
- safety and privacy notice explaining local/hosted processing;
- `Discover shape` action;
- progressive enhancement baseline using a normal multipart form.

### 2. Shape explorer

Purpose: show the uploaded website as an inspectable system graph.

Required UI:

- live preview iframe or sandboxed preview pane;
- DOM/tree graph and searchable variable list;
- tabs for HTML, CSS, JavaScript, assets, behavior, policies, and provenance;
- hover/select synchronization between preview and variable rows;
- ability to click a DOM node or drag a bounding box in the preview to define a sub-shape;
- breadcrumbs from whole website to selected component shape;
- confidence and evidence panel for inferred labels.

### 3. Variable control surface

Purpose: let users make simple tweaks.

Required UI:

- generated controls by type: text inputs, color pickers, range sliders, select lists, token editors, code-safe toggles, and structured object editors;
- before/after value display;
- dependency warnings when one value affects multiple selectors or nodes;
- preview-only proposals until saved;
- reset, duplicate variant, and save-as-new-shape actions;
- accessibility feedback for text, contrast, labels, and focusable controls.

### 4. Visual data mapper

Purpose: map source shape elements to destination shape elements.

Required UI:

- left column for source shape elements;
- right column for destination shape template, selected existing shape, or generated blank shape;
- central relation canvas supporting direct mapping, one-to-many, many-to-one, conditional mapping, lookup, formula, template, generate, ignore, and unresolved relation types;
- suggested mappings with confidence and explanation;
- transform picker for copy, translate, transmute, derive, split, combine, tokenize, componentize, restructure, or generate;
- warnings for lossy, irreversible, permission-blocked, or unsupported mappings;
- keyboard-accessible non-canvas mapping table fallback.

### 5. Transmutation studio

Purpose: change the source shape into a new shape.

Required UI:

- target shape selector: blank website, differently configured website, reusable component, section pack, design-token set, dashboard, landing page, documentation page, or custom registered shape ID;
- transformation recipe builder with steps such as extract section, rename variables, convert CSS values to tokens, reorganize layout, split a card list into data-driven cards, change navigation structure, or wrap a subtree as a component;
- side-by-side source/proposed/destination preview;
- promptable but reviewable AI-assist area for candidate transformations, never direct unreviewed execution;
- simulation result showing changed files, generated artifacts, unresolved values, and validation results.

### 6. Save, export, and run report screen

Purpose: preserve the new shape and produce usable output.

Required UI:

- save current draft to existing shape ID or save as new registered shape ID;
- export transformed `index.htm`, `styles.css`, and `scripts.js`;
- export `.posh` bundle with systems, elements, mappings, transforms, surface, workflow, policies, snapshot, and run report;
- compare source and destination shapes;
- show provenance: upload files, discovered values, user decisions, AI suggestions if any, approvals, validation outcomes, generated outputs;
- shareable local demo summary.

## Core workflow

```text
UPLOAD FILES
  → DISCOVER WEBSITE SHAPE
  → REGISTER SOURCE SHAPE ID
  → EXPLORE VARIABLES AND SUB-SHAPES
  → CHOOSE TWEAK, COMPONENT EXTRACTION, OR TRANSMUTATION TARGET
  → MAP SOURCE VALUES TO DESTINATION VALUES
  → TRANSMUTATE STRUCTURE/VALUES
  → SIMULATE AND VERIFY
  → SAVE NEW SHAPE ID OR VERSION
  → EXPORT WEBSITE FILES AND `.posh` EVIDENCE
```

## Example scenarios

### A. Tweak one value

1. User uploads a small site.
2. PortaShape discovers a `primaryColor` variable from repeated CSS values.
3. User changes it from blue to green.
4. Preview updates.
5. User saves a new website-shape version named `campaign-site.green-variant`.
6. Export includes changed `styles.css`, a snapshot, and a run report.

### B. Transmutate a single `div` into a reusable card shape

1. User selects a product-card `div` in the preview.
2. PortaShape identifies image, title, description, price, CTA link, hover style, and click behavior.
3. User registers it as `shape.product-card.basic`.
4. User maps the card fields to a reusable component template.
5. PortaShape transmutates the raw DOM/CSS/JS into a component shape with variables and policies.
6. User exports `.posh` plus example HTML/CSS/JS for reuse.

### C. Translate a one-page site into a dashboard shape

1. User selects destination shape `dashboard.ops-basic`.
2. PortaShape maps hero statistics to metric cards, navigation to dashboard tabs, CTA links to action buttons, and sections to panels.
3. Unsupported marketing copy is marked as unresolved or moved to notes.
4. User reviews suggested relations and accepts selected transmutations.
5. Simulation produces a dashboard layout and validation report.
6. User saves destination shape `dashboard.ops-basic.from-marketing-site`.

### D. Reconfigure a website without changing its shape kind

1. User chooses destination `website` and recipe `brand refresh`.
2. PortaShape translates colors, fonts, spacing, and motion values into a new token set.
3. Structure remains mostly intact.
4. User saves the new configured website as a variant with lineage back to the source shape.

## `.posh` artifacts produced

The demo should produce a composed bundle, even when also exporting ordinary website files.

Recommended bundle contents:

- `system` — uploaded website declaration and discovered graph;
- `snapshot` — original uploaded file state and destination output state;
- `surface` — generated explorer, variable controls, mapper, and transmutation studio configuration;
- `mapping` — source-to-destination relations;
- `transform` — tweak, translation, and transmutation operations;
- `workflow` — upload, discovery, mapping, simulation, save, export steps;
- `policy` — validation rules for accessibility, security, value ranges, and shape compatibility;
- `run` — executed simulation/save/export report;
- `library` — reusable component shapes, token controls, transform recipes, and Web-Native Runtime patterns used.

The artifact must distinguish:

- source shape ID;
- selected sub-shape IDs;
- proposed shape ID;
- destination shape ID;
- saved version IDs;
- source-native paths versus semantic IDs;
- translated values versus transmutated structures;
- unresolved and intentionally ignored values.

## Web-Native Runtime implementation requirements

The demo should use the repository's Web-Native Runtime Library as a normal PortaShape toolset.

### Ownership

- Server/database or local demo backend owns saved shapes, artifacts, uploads, validation, provenance, and run records.
- URLs own selected shape, current view, selected mapper target, and saved comparison routes.
- Native controls own submitted proposals in upload, edit, mapping, and save forms.
- htmx owns upload requests, discovery jobs, variable-list filtering, preview refreshes, mapper updates, validation panels, OOB status/toast updates, and export actions.
- Alpine owns local panel state, drag hover, selected rows, disclosure state, transient preview controls, keyboard focus helpers, and unsaved local UI affordances.
- Isolated JavaScript islands own preview iframe instrumentation, visual selection overlays, graph/canvas mapping, code editor widgets, and any high-frequency rendering.
- Semantic browser events coordinate upload completion, shape selection, variable proposal, mapper relation creation, transmutation simulation completion, toast announcements, and shell close/open behavior.

### Required component patterns

- Stable Alpine shell with htmx interior for explorer panels, mapper drawers, and transmutation modals.
- htmx-replaceable components with disposable Alpine behavior for variable rows, inline edit forms, and validation cards.
- htmx-only server components for paginated variable tables and run-report fragments.
- Alpine-only local components for disclosure, tabs over already-loaded content, simple filters, and compare toggles.
- Isolated JavaScript islands for preview selection, DOM bounding boxes, source code highlighting, and relation canvas.

### Progressive enhancement

The demo must remain understandable without JavaScript:

- uploads submit through a normal form;
- discovered variables can be viewed as server-rendered tables;
- mappings can be edited with accessible forms instead of only a canvas;
- shape save/export actions are normal POST actions;
- direct URLs open saved shape, mapper, comparison, and run-report pages.

## Validation and safety

The demo must include visible validation for:

- malformed HTML/CSS/JS;
- unsafe script execution and sandbox restrictions;
- duplicate DOM IDs and inaccessible controls;
- color contrast and missing labels/alt text;
- broken asset references and links;
- unsupported JavaScript behavior;
- irreversible or lossy transmutations;
- unmapped required destination fields;
- output file generation errors;
- shape ID collisions and version conflicts.

Security constraints:

- uploaded scripts must never execute in the parent PortaShape UI;
- previews must use sandboxing and clear trust boundaries;
- generated HTML must escape untrusted text;
- AI-assisted transform suggestions must be structured, reviewed, and recorded before use;
- secrets or credentials must be references, not embedded artifacts;
- export bundles must indicate whether raw uploaded content is included.

## Data model sketch

Minimum records for the demo backend:

- `Shape` — `id`, `label`, `kind`, `status`, `createdAt`, `updatedAt`, `lineage`, `currentVersionId`;
- `ShapeVersion` — `id`, `shapeId`, `version`, `sourceFiles`, `artifactRef`, `snapshotRef`, `validationSummary`;
- `ShapeElement` — `id`, `shapeVersionId`, `label`, `kind`, `sourcePath`, `semanticPath`, `parentId`, `valueRef`, `confidence`, `evidence`;
- `ShapeVariable` — `id`, `elementId`, `label`, `type`, `scope`, `owner`, `currentValue`, `proposedValue`, `constraints`, `editable`, `dependencies`;
- `ShapeRelation` — `id`, `sourceElementId`, `destinationElementId`, `relationType`, `operation`, `transformRef`, `confidence`, `loss`, `status`;
- `TransformRecipe` — `id`, `label`, `inputShapeKinds`, `outputShapeKinds`, `steps`, `policies`, `reversibility`, `trustLevel`;
- `RunReport` — `id`, `workflowId`, `sourceShapeId`, `destinationShapeId`, `inputs`, `outputs`, `decisions`, `validation`, `warnings`, `provenance`.

## MVP boundary

The first build should support:

- upload of one three-file website package;
- server-side parsing and discovery of HTML/CSS plus conservative JavaScript static extraction;
- shape registry dashboard for local demo storage;
- variable list grouped by content/design/structure/behavior;
- live preview with selectable DOM nodes;
- saving the whole website as a shape;
- saving a selected DOM subtree as a component shape;
- editing a small set of variable types: text, links, colors, spacing, font sizes, booleans, simple script constants;
- mapping table and accessible mapper fallback;
- at least three transmutation recipes: brand refresh, component extraction, and landing-page-to-dashboard;
- export of transformed files and `.posh` bundle;
- validation/report screen with provenance.

Explicitly defer:

- arbitrary JavaScript rewriting;
- multi-page project import;
- asset pipelines beyond referenced file reporting;
- live external website crawling;
- collaborative editing;
- production credentialed deployments;
- unreviewed AI-generated transformations.

## Acceptance criteria

A successful showcase lets a user complete these tasks without developer help:

1. upload `index.htm`, `styles.css`, and `scripts.js`;
2. see the website rendered in a safe preview;
3. see a useful list of discovered variables with labels, IDs, types, and source evidence;
4. change at least one content value and one design value;
5. save the changed site as a new registered shape version;
6. select a single `div` and save it as a reusable component shape;
7. choose a destination shape and map at least five source values to it;
8. run a transmutation simulation and review warnings;
9. export transformed website files;
10. export a `.posh` bundle containing system, snapshot, surface, mapping, transform, workflow, policy, and run evidence;
11. reload the dashboard and reopen both the source and saved destination shapes.


<!-- END docs/11-website-shape-translator-showcase-spec.md -->

---

<!-- BEGIN docs/12-simple-shape-transmutation-examples.md -->

# Simple Shape Translation and Transmutation Examples

## Purpose

This document lists three dozen primary, simple showcase examples for PortaShape users to practice importing a source shape, inspecting labeled values, mapping those values, translating compatible values, transmutating structures when needed, and saving the result as a new registered shape.

These examples are intentionally smaller than the full Website Shape Translator Showcase. They should become playground fixtures, sample `.posh` bundles, guided tutorials, and UI smoke tests for the visual mapper, variable controls, transform recipes, validation panels, and shape load/save/manage dashboard.

## How to use these examples

Each example should provide:

- a source shape with a stable shape ID;
- a destination shape or template with a stable shape ID;
- a small set of labeled variables;
- one or more suggested mappings;
- at least one user-editable control;
- a preview of source, proposed, and destination values;
- a save-as-new-shape action;
- a `.posh` export containing the mapping, transform, workflow, policy, snapshot, and run evidence.

## Three dozen simple examples

| # | Example | Source shape | Destination shape | What users can try |
| --- | --- | --- | --- | --- |
| 1 | Display name formatter | `person.name_parts` | `person.display_name` | Combine first, middle, and last names into one labeled display value. |
| 2 | Split full name | `person.full_name` | `person.name_parts` | Split one name string into first, middle, last, suffix, and unresolved tokens. |
| 3 | Contact card to CRM lead | `contact.card` | `crm.lead` | Map name, email, phone, company, title, and notes into a CRM-shaped record. |
| 4 | Address label to structured address | `address.shipping_label` | `address.structured` | Parse multiline label text into street, city, region, postal code, and country. |
| 5 | Structured address to mailing label | `address.structured` | `address.shipping_label` | Compose address fields into a printable label with locale-aware formatting. |
| 6 | CSV row to profile card | `csv.customer_row` | `ui.profile_card` | Map tabular fields into visible card labels, badges, and links. |
| 7 | Profile card to CSV row | `ui.profile_card` | `csv.customer_row` | Flatten a UI component shape into exportable tabular data. |
| 8 | Blog metadata to social preview | `blog.article_meta` | `social.preview_card` | Translate title, excerpt, author, image, date, and URL into Open Graph-style preview fields. |
| 9 | Social preview to newsletter block | `social.preview_card` | `email.newsletter_block` | Transmutate preview content into an email-safe content block. |
| 10 | Product card to ecommerce item | `ui.product_card` | `commerce.product_record` | Map image, title, SKU, price, sale label, CTA, and inventory hint into product data. |
| 11 | Ecommerce item to product card | `commerce.product_record` | `ui.product_card` | Generate a reusable product card from structured product data. |
| 12 | Menu links to navigation bar | `content.link_list` | `ui.nav_bar` | Turn labeled links into ordered navigation items with active-state options. |
| 13 | Navigation bar to sitemap | `ui.nav_bar` | `site.sitemap` | Export navigational structure into a sitemap-style shape with paths and labels. |
| 14 | Task list to kanban board | `tasks.flat_list` | `workflow.kanban_board` | Group task records by status and transmutate them into columns and cards. |
| 15 | Kanban board to task list | `workflow.kanban_board` | `tasks.flat_list` | Flatten columns back into task rows while preserving status. |
| 16 | Event details to calendar entry | `event.public_details` | `calendar.entry` | Map title, date, time, location, description, and registration link into a calendar item. |
| 17 | Calendar entry to event hero | `calendar.entry` | `ui.event_hero` | Generate a page hero with date badge, headline, location, and CTA. |
| 18 | FAQ list to accordion | `content.faq_pairs` | `ui.faq_accordion` | Turn question/answer rows into accessible disclosure items. |
| 19 | Accordion to FAQ JSON | `ui.faq_accordion` | `content.faq_pairs` | Extract visible questions and answers from a component into portable content data. |
| 20 | Testimonial quotes to carousel | `content.testimonials` | `ui.carousel` | Map quotes, names, roles, images, and order into a carousel shape. |
| 21 | Carousel to static quote grid | `ui.carousel` | `ui.quote_grid` | Transmutate interactive slides into a non-interactive responsive grid. |
| 22 | Color palette to CSS variables | `design.palette` | `css.custom_properties` | Translate labeled colors into `--color-*` CSS custom properties. |
| 23 | CSS variables to design tokens | `css.custom_properties` | `design.tokens` | Infer token names, roles, scopes, and aliases from CSS variable declarations. |
| 24 | Font scale to CSS classes | `design.type_scale` | `css.utility_classes` | Generate utility classes from font sizes, line heights, and weights. |
| 25 | Pixel spacing to rem spacing | `css.pixel_spacing` | `css.rem_spacing` | Convert spacing values and show rounding, base-size, and loss metadata. |
| 26 | Theme options to user preferences | `theme.global_settings` | `user.theme_options` | Separate global defaults from personal options such as dark mode and density. |
| 27 | User preferences to app settings | `user.theme_options` | `app.settings_patch` | Promote selected personal preferences into proposed app-level settings with approval warnings. |
| 28 | Form fields to validation schema | `html.form_controls` | `schema.validation_rules` | Extract labels, names, required state, input types, min/max values, and patterns. |
| 29 | Validation schema to form UI | `schema.validation_rules` | `html.form_controls` | Generate accessible form controls from field definitions and constraints. |
| 30 | API response to table view | `api.record_collection` | `ui.data_table` | Map fields to columns, labels, sort options, filters, and row actions. |
| 31 | Table view to API query | `ui.data_table_state` | `api.query_params` | Translate table filters, sorting, pagination, and selected columns into query parameters. |
| 32 | Status enum to progress tracker | `workflow.status_enum` | `ui.progress_tracker` | Map statuses into ordered steps with labels, current-state rules, and completed styling. |
| 33 | Progress tracker to status enum | `ui.progress_tracker` | `workflow.status_enum` | Extract an enum and transition hints from visible progress steps. |
| 34 | Image metadata to gallery card | `asset.image_metadata` | `ui.gallery_card` | Map filename, alt text, dimensions, caption, credit, and tags into a gallery component. |
| 35 | Gallery card to asset manifest | `ui.gallery_card` | `asset.manifest_item` | Extract asset references and captions into a reusable manifest record. |
| 36 | Mini landing section to component shape | `html.landing_section` | `component.reusable_section` | Select a heading/body/button/image `section` or `div`, assign a shape ID, expose variables, and save it as reusable. |

## Coverage map

Together these examples exercise PortaShape's basic shape operations:

- **copy** — direct value movement, such as email to email;
- **combine** — several labeled values becoming one labeled value;
- **split** — one compound value becoming several labeled values;
- **translate** — equivalent values moving across format or context boundaries;
- **transmutate** — structure changing shape, such as a task list becoming kanban columns;
- **flatten** — nested UI or workflow structure becoming rows or records;
- **componentize** — selected markup or repeated data becoming a reusable component shape;
- **tokenize** — raw design values becoming semantic design tokens;
- **promote** — local option values becoming proposed settings with policy checks;
- **extract** — UI or file content becoming structured data;
- **generate** — structured data becoming UI, CSS, schema, or files;
- **verify** — checking loss, unresolved values, accessibility, safety, ownership, and compatibility.

## Recommended playground progression

1. Start with examples 1-5 to teach combine, split, copy, and formatting.
2. Use examples 6-13 to teach flattening, component generation, and navigation/content shape movement.
3. Use examples 14-21 to teach structural transmutation between lists, boards, accordions, grids, and carousels.
4. Use examples 22-27 to teach design tokens, CSS values, settings, options, and promotion policies.
5. Use examples 28-33 to teach forms, schemas, API/table translation, and workflow status mapping.
6. Use examples 34-36 to lead into visual selection, asset extraction, and the larger Website Shape Translator Showcase.


<!-- END docs/12-simple-shape-transmutation-examples.md -->

---

<!-- BEGIN spec/PORTASHAPE_0.1_CONCEPTUAL_SCHEMA.md -->

# PortaShape 0.1 Conceptual Schema

## Status

This is a coherent **conceptual draft**, not a final normative specification. It consolidates the uploaded concept and example materials into a single artifact model suitable for implementation planning and schema prototyping.

## Serialization

- File extension: `.posh`
- Canonical serialization: UTF-8 JSON
- Root key: `portaShape`
- Format version: semantic or compatible version string beginning with `0.1`
- Unknown namespaced extension keys should be preservable even when not executable.

## Minimal artifact

```json
{
  "portaShape": {
    "formatVersion": "0.1",
    "kind": "mapping",
    "id": "example.mapping",
    "name": "Example Mapping",
    "mappings": []
  }
}
```

## Root fields

| Field | Required | Meaning |
| --- | :---: | --- |
| `formatVersion` | yes | `.posh` serialization version. |
| `kind` | yes | Primary artifact kind. |
| `id` | recommended | Stable artifact identity. |
| `name` | recommended | Human-readable name. |
| `description` | no | Purpose and context. |
| `imports` | no | Other artifacts or library packages. |
| `systems` | by use | Connected or referenced systems. |
| `elements` | no | Embedded element definitions or snapshot content. |
| `surfaces` | no | Control and view compositions. |
| `mappings` | no | Element relationships with execution semantics. |
| `transforms` | no | Reusable operations. |
| `workflows` | no | Orchestrated steps and approvals. |
| `policies` | no | Validation, permissions, and governance. |
| `settings` | no | Global or structural configuration. |
| `options` | no | User/account/session selections. |
| `unresolved` | no | Explicit unresolved values or relationships. |
| `extensions` | no | Namespaced additions. |
| `metadata` | no | Authors, dates, versions, signatures, notes, provenance summary. |

## Artifact kinds

Allowed initial values:

```text
system | snapshot | surface | mapping | transform | workflow | policy | run | library | bundle
```

A parser may support legacy or experimental kinds through an extension or migration layer.

## System declaration

```json
{
  "id": "source-site",
  "type": "website",
  "adapter": {
    "id": "example.website-adapter",
    "version": "1.0.0"
  },
  "environment": "production",
  "connectionProfile": "secrets://connections/source-site",
  "schema": "library://schemas/example-site@1",
  "capabilities": ["read", "observe"],
  "version": "2026.07"
}
```

A system declaration must not require raw credentials.

## Element declaration

```json
{
  "id": "source-site#theme.colors.primary",
  "system": "source-site",
  "kind": "value",
  "path": "theme.colors.primary",
  "name": "Primary color",
  "semanticRole": "color.action.primary",
  "valueType": "color",
  "scope": "settings",
  "authority": "source-site",
  "capabilities": ["read", "propose"],
  "constraints": {
    "format": "hex"
  }
}
```

## Scope values

Initial core scopes:

```text
settings | options | runtime | content | code | derived | reference | secret-reference
```

Custom scopes use namespaced values.

## Mapping declaration

```json
{
  "id": "map-primary-color",
  "source": "source-site#theme.colors.primary",
  "destination": "destination-site#brand.actionColor",
  "relation": "semantic-equivalent",
  "operation": "translate",
  "transform": "color.hex-to-rgb",
  "direction": "source-to-destination",
  "loss": "lossless",
  "confidence": 0.98,
  "explanation": "Both values control the primary interactive brand color.",
  "validation": ["policy://brand/primary-color"]
}
```

## Operations

Initial operation values:

```text
copy | map | translate | transmute | derive | generate | synchronize | ignore | unresolved
```

## Relationship cardinality

A mapping can use string references or arrays:

- one source, one destination;
- one source, multiple destinations;
- multiple sources, one destination;
- multiple sources, multiple destinations.

## Transform declaration

```json
{
  "id": "spacing-scale-from-base",
  "kind": "formula",
  "inputs": [
    {"name": "base", "type": "number"}
  ],
  "outputs": [
    {"name": "scale", "type": "object"}
  ],
  "expression": {
    "space.1": "base * 0.25",
    "space.2": "base * 0.5",
    "space.3": "base",
    "space.4": "base * 1.5"
  },
  "deterministic": true,
  "loss": "generated",
  "trust": "declarative"
}
```

## Loss values

```text
lossless | lossy | approximate | inferred | generated | non-deterministic | unresolved
```

Reversibility is a separate boolean or strategy declaration.

## Surface declaration

```json
{
  "id": "theme-tuner",
  "name": "Theme Tuner",
  "renderer": "library://portashape/web-native",
  "bindings": [
    {
      "element": "source-site#theme.colors.primary",
      "control": "color",
      "mode": "propose-and-preview"
    }
  ],
  "layout": {
    "type": "inspector"
  },
  "permissions": {
    "commit": ["role:designer-lead"]
  }
}
```

## Event contract

```json
{
  "id": "theme-preview-applied",
  "kind": "fact",
  "producer": "surface:theme-tuner",
  "scope": "workspace",
  "payloadSchema": {
    "artifactId": "string",
    "changedElementIds": "string[]"
  },
  "version": "1"
}
```

Events should describe domain meaning rather than implementation detail.

## Workflow declaration

```json
{
  "id": "promote-theme",
  "steps": [
    {"id": "snapshot", "action": "snapshot", "system": "destination-site"},
    {"id": "simulate", "action": "simulate", "mapping": "theme-mapping"},
    {"id": "validate", "action": "validate", "policies": ["brand", "accessibility"]},
    {"id": "approve", "action": "approval", "role": "design-lead"},
    {"id": "execute", "action": "apply", "mapping": "theme-mapping"},
    {"id": "verify", "action": "validate-destination"}
  ]
}
```

## Policy declaration

Policies may contain assertions, rules, severity, scope, required evidence, and gating behavior.

```json
{
  "id": "all-source-routes-resolved",
  "assert": "count(unresolved where category == 'route') == 0",
  "severity": "error",
  "gate": "execution"
}
```

## Unresolved declaration

```json
{
  "id": "unresolved-widget-legacy-carousel",
  "source": "source-site#components.legacyCarousel",
  "reason": "Destination has no equivalent component or adapter capability.",
  "severity": "warning",
  "candidates": ["destination-site#components.gallery"],
  "requiresDecision": true,
  "canContinue": true
}
```

## Run report

A run artifact should resolve exact imported versions and include:

- workflow or mapping ID;
- actor;
- start and completion times;
- source and destination system versions;
- artifact, adapter, transform, and policy versions;
- resolved inputs;
- writes and outputs;
- approvals;
- validation results;
- warnings, errors, unresolved values;
- provenance links;
- rollback or compensation information;
- final status.

## Imports and layering

```json
{
  "imports": [
    {
      "ref": "library://platform-a-to-b@2",
      "as": "base"
    },
    {
      "ref": "./organization-overrides.posh",
      "as": "organization"
    }
  ]
}
```

Layer resolution must be deterministic and reveal conflicts before execution.

## Extensions

Extension keys use a reverse-domain or package namespace:

```json
{
  "extensions": {
    "dev.portashape.visual-regression": {
      "baseline": "artifact://screenshots/theme-v4"
    }
  }
}
```

Core parsers preserve unknown extensions. Execution requires a compatible extension provider.

## Canonical formatting

A future normative specification should define:

- key order or canonicalization algorithm;
- numeric and date normalization;
- stable reference resolution;
- hashing and signatures;
- schema URIs;
- comments or annotation strategy;
- partial-file composition;
- migration between versions.

## Relationship to the MVP example catalog

The extracted examples use a smaller conceptual shape with `source`, `destination`, `mappings`, `settings`, and `options`. They remain valid teaching artifacts. An implementation can either support them directly as a simple profile or migrate them into the richer multi-system schema described here.

<!-- END spec/PORTASHAPE_0.1_CONCEPTUAL_SCHEMA.md -->

---

<!-- BEGIN SYNTHESIS_MAP.md -->

# PortaShape Synthesis Map

## Purpose

This map records how the uploaded materials were incorporated into the new PortaShape product canon. It also distinguishes canonical documents from preserved source material.

## Source-to-canon mapping

### `PortaShape.md`

Primary contributions:

- mapping, translation, and transmutation;
- visual source-to-destination relationships;
- settings versus options;
- website transfer and value-for-value reconstruction;
- snapshots, comparison, synchronization, preview, validation, provenance, security, versioning, unresolved values, reusable libraries, and `.posh` artifacts.

Canonical destinations:

- `docs/01-purpose-and-positioning.md`
- `docs/02-system-model-and-vocabulary.md`
- `docs/04-capabilities-and-modules.md`
- `docs/06-posh-artifact-model.md`
- `docs/08-use-cases-and-workflows.md`
- `docs/09-governance-security-and-validation.md`
- `spec/PORTASHAPE_0.1_CONCEPTUAL_SCHEMA.md`

Resolution applied:

The runtime interface is no longer described as a neighboring product. It is PortaShape’s operational surface, while mapping and transfer are relationship and execution capabilities over the same system model.

### `tuner.md`

Primary contributions:

- generated interfaces from data, code, schemas, styles, brand, motion, content, and runtime behavior;
- dynamic control surfaces;
- runtime feedback and tuning;
- pattern discovery;
- automatic, guided, manual, and adaptive generation;
- shared operational language across roles;
- connection, interpretation, control, composition, runtime, analysis, governance, and export layers.

Canonical destinations:

- `docs/01-purpose-and-positioning.md`
- `docs/02-system-model-and-vocabulary.md`
- `docs/03-product-experience.md`
- `docs/04-capabilities-and-modules.md`
- `docs/05-architecture.md`
- `docs/08-use-cases-and-workflows.md`

Resolution applied:

The “runtime interface” becomes PortaShape Explore, Shape, Runtime, and Surface capabilities. Its controls, observations, and patterns use the same identities and artifacts as mapping, comparison, and migration.

### `posh.posh`

Primary contributions:

- three dozen MVP-ready conceptual examples progressing from direct copy through visual componentization;
- examples of settings, options, unit conversion, lookups, combine/split transforms, snapshots, CRM transfer, content migration, and complete runtime-assisted migration.

Canonical destinations:

- MVP JSON `.posh` playground fixtures in `examples/`, including all thirty-six simple examples plus upgraded legacy catalog examples;
- example index in `examples/README.md`;
- conceptual format consolidation in `docs/06-posh-artifact-model.md` and `spec/PORTASHAPE_0.1_CONCEPTUAL_SCHEMA.md`.

Resolution applied:

The source catalog is preserved under `source-material/`, while its code blocks are extracted as machine-readable examples. The richer schema adds artifact kinds for surfaces, workflows, policies, runs, and libraries without invalidating the simple teaching profile.

### `htmxalpine04-main.zip`

Primary contributions:

- explicit state authority and DOM-writer doctrine;
- web-native progressive enhancement;
- native controls and routes;
- Alpine.js local interaction patterns;
- htmx request, swap, history, and multi-region patterns;
- semantic event contracts;
- lifecycle, accessibility, security, testing, and production discipline;
- onboarding curriculum, companion guides, source audit, and showcase ideas.

Canonical destinations:

- preserved corpus under `libraries/web-native-runtime/reference/`;
- product placement in `docs/07-web-runtime-library.md`;
- architectural integration in `docs/02-system-model-and-vocabulary.md`, `docs/03-product-experience.md`, `docs/05-architecture.md`, and `docs/09-governance-security-and-validation.md`;
- summarized reusable patterns in `libraries/web-native-runtime/PORTASHAPE_PATTERNS.md`.

Resolution applied:

The repository becomes a PortaShape library and reference renderer corpus rather than a separate workspace. Its technology-specific version baseline remains owned by its own manifest.

## Canonical versus reference documents

### Canonical

The top-level README, numbered documents, conceptual schema, example index, library wrapper, and roadmap define the new unified product story.

### Reference

Files under `source-material/` and `libraries/web-native-runtime/reference/` preserve the uploaded sources. They provide detail, evidence, examples, and implementation education but do not override the unified terminology in the canon.

## Major conceptual reconciliations

1. **One product:** runtime control, mapping, migration, comparison, and libraries operate on one system graph.
2. **One purpose:** make digital systems visible, operable, and portable.
3. **One artifact family:** `.posh` stores not only mappings but systems, surfaces, transforms, workflows, policies, libraries, snapshots, and runs.
4. **One authority model:** settings, options, runtime state, source truth, proposals, and previews remain distinct.
5. **One workspace:** Explore, Shape, Map, Run, Compare, and Library are lenses, not isolated compartments.
6. **One implementation library placement:** Alpine.js + htmx is a web-native runtime library under PortaShape, not the product boundary.

<!-- END SYNTHESIS_MAP.md -->
