import { FormEvent, useEffect, useState } from 'react';
import { Activity, ArrowRight, BookOpen, Boxes, Check, Code2, Download, GitBranch, KeyRound, LogOut, Plus, ShieldCheck, Terminal, UserRound } from 'lucide-react';
import ControlRoom from './App';
import { platformApi, type Project, type User, type UserProfile } from './platformApi';

const base = (import.meta.env.VITE_BASE_PATH || import.meta.env.BASE_URL || '/').replace(/\/$/, '');
const href = (path = '') => `${base}${path.startsWith('/') ? path : `/${path}`}`;

function Brand() {
  return <a className="site-brand" href={href('/')}><span><Boxes size={19} /></span>POLYFORM</a>;
}

function SiteNav({ user }: { user: User | null }) {
  return <header className="site-nav"><Brand /><nav><a href={href('/docs')}>Docs</a><a href={href('/download')}>Download</a>{user ? <a className="nav-account" href={href('/dashboard')}><UserRound size={14} />{user.username}</a> : <><a href={href('/login')}>Sign in</a><a className="nav-cta" href={href('/signup')}>Create account</a></>}</nav></header>;
}

function Layout({ user, children }: { user: User | null; children: React.ReactNode }) {
  return <div className="public-shell"><SiteNav user={user} />{children}<footer className="site-footer"><Brand /><span>Several tested versions. Different mixes. Better failure data.</span><div><a href={href('/docs')}>Documentation</a><a href={href('/download')}>CLI</a></div></footer></div>;
}

export function Landing({ user }: { user: User | null }) {
  const [projects, setProjects] = useState<Project[]>([]);
  useEffect(() => { platformApi.projects().then(setProjects).catch(() => undefined); }, []);
  return <Layout user={user}><main className="landing">
    <section className="landing-hero"><div className="hero-copy"><div className="site-kicker"><GitBranch size={14} />Software diversity, written by coding agents</div><h1>Keep one implementation bug from reaching everyone.</h1><p>Your coding agents create several independent implementations of every function in your specification. Each installation runs a different combination. Polyform connects failures to the implementations that were running and lets you stop distributing suspicious ones.</p><div className="hero-actions"><a className="primary-cta" href={user ? href('/dashboard') : href('/signup')}>{user ? 'Open your projects' : 'Create a free project'}<ArrowRight size={17} /></a><a className="secondary-cta" href={href('/docs')}>See how it works</a></div></div>
      <div className="composition-demo"><div className="demo-title"><span>one installed app</span><b>1,953,125</b><small>possible combinations</small></div>{['read ZIP header','decode filename','make path safe','decompress file','check file data'].map((name,index)=><div className="demo-function" key={name}><span>{name}</span><div>{Array.from({length:5},(_,variant)=><i className={variant===index%5?'selected':''} key={variant}/>)}</div></div>)}<div className="demo-health"><ShieldCheck size={17}/><span>Bad decoder found. Installations get a replacement.</span></div></div>
    </section>
    <section className="plain-example"><div className="section-heading"><span>A CONCRETE EXAMPLE</span><h2>Suppose your app needs to decode a filename.</h2></div><div className="example-flow"><article><b>1</b><h3>Specify the behavior</h3><p>Describe every valid input, output, error, security rule, and important example.</p></article><ArrowRight/><article><b>2</b><h3>Let agents write the code</h3><p><code>polyform generate --count 5</code> creates shared tests and five independent decoders.</p></article><ArrowRight/><article><b>3</b><h3>Compare real results</h3><p>If one decoder appears mostly in failed runs, quarantine it. Other decoders take its place.</p></article></div></section>
    <section className="how"><div className="section-heading"><span>THE WHOLE LOOP</span><h2>Polyform adds four ideas to a normal software project.</h2></div><div className="feature-grid">
      <article><span><BookOpen /></span><b>Describe the function</b><p>Write down exactly what it accepts, returns, and must never do. Tests enforce those rules.</p></article>
      <article><span><Code2 /></span><b>Have agents write several versions</b><p>Each version follows the same contract, so any one can be used.</p></article>
      <article><span><Boxes /></span><b>Give installations different combinations</b><p>Your app contains every accepted version. Polyform tells each installation which ones to use.</p></article>
      <article><span><Activity /></span><b>Remove versions that fail</b><p>Your app reports success or failure—not user files. The dashboard makes risky versions stand out.</p></article>
    </div></section>
    <section className="how"><div className="section-heading"><span>WHY THIS IS POSSIBLE NOW</span><h2>AI can write enough code to make diversity practical.</h2><p>Coding agents can produce and test independent implementations at a scale that was too expensive when every version had to be handwritten. At the same time, advanced AI is making vulnerability discovery and exploitation faster. Shipping different implementations reduces the chance that one flaw exposes every installation at once. It cannot guarantee that an unknown vulnerability is already fixed, but a safe alternative may already be installed and ready to distribute when another version is quarantined.</p></div></section>
    <section className="local-first"><div><span className="site-kicker"><Terminal size={14}/>Works with your development tools</span><h2>You specify the behavior. Your agents write the implementations.</h2><p>Keep using your editor, test framework, compiler, and source repository. Polyform starts Codex, checks every generated candidate on your computer, distributes different combinations to installations, and shows you which versions are tied to failures.</p><a href={href('/docs/create-project')}>Build your first Polyform project <ArrowRight size={15}/></a></div><pre><code><em>$</em> polyform init{`\n`}<em>$</em> polyform generate --count 5{`\n`}<em>✓</em> 5 implementations per function{`\n`}<em>$</em> polyform check{`\n`}<em>✓</em> all shared tests passed</code></pre></section>
    {projects.length > 0 && <section className="explore"><div className="section-heading"><span>OPEN PROJECTS</span><h2>Built in public</h2></div><div className="project-cards">{projects.map(project=><ProjectCard project={project} key={project.id}/>)}</div></section>}
  </main></Layout>;
}

function ProjectCard({ project }: { project: Project }) {
  return <a className="project-card" href={href(`/${project.owner}/${project.slug}`)}><span className="project-owner">{project.owner}</span><h3>{project.name}</h3><p>{project.description || 'An open Polyform project.'}</p><small><GitBranch size={13}/>{project.slug}<ArrowRight size={14}/></small></a>;
}

export function AuthPage({ mode, onUser }: { mode: 'signup'|'login'; onUser: (user: User) => void }) {
  const [error,setError]=useState(''); const [busy,setBusy]=useState(false);
  async function submit(event: FormEvent<HTMLFormElement>) { event.preventDefault(); setBusy(true); setError(''); const values=Object.fromEntries(new FormData(event.currentTarget)); try { const user=mode==='signup' ? await platformApi.signup({username:String(values.username),email:String(values.email),password:String(values.password)}) : await platformApi.login({username:String(values.username),password:String(values.password)}); onUser(user); window.location.href=href('/dashboard'); } catch (e) { setError(e instanceof Error?e.message:'Unable to continue'); setBusy(false); } }
  return <Layout user={null}><main className="auth-layout"><section className="auth-intro"><Brand/><h1>{mode==='signup'?'Create your Polyform account.':'Welcome back.'}</h1><p>{mode==='signup'?'Create public projects, publish function contracts and releases, and see which code versions fail most often.':'Sign in to manage projects, releases, code versions, and failure data.'}</p><div><Check/>Tests and builds run on your computer</div><div><Check/>Source and function contracts stay public</div><div><Check/>Failure reports exclude user content</div></section><form className="auth-card" onSubmit={submit}><div className="site-kicker"><KeyRound size={14}/>{mode==='signup'?'CREATE ACCOUNT':'SIGN IN'}</div><label>Username<input name="username" required autoComplete="username" placeholder="ada" pattern="[A-Za-z0-9][A-Za-z0-9_-]{2,31}"/></label>{mode==='signup'&&<label>Email<input name="email" required type="email" autoComplete="email" placeholder="ada@example.com"/></label>}<label>Password<input name="password" required minLength={8} type="password" autoComplete={mode==='signup'?'new-password':'current-password'}/></label>{error&&<p className="form-error">{error}</p>}<button className="primary-cta" disabled={busy}>{busy?'Working…':mode==='signup'?'Create account':'Sign in'}<ArrowRight size={16}/></button><p className="auth-switch">{mode==='signup'?'Already have an account?':'New to Polyform?'} <a href={href(mode==='signup'?'/login':'/signup')}>{mode==='signup'?'Sign in':'Create one'}</a></p></form></main></Layout>;
}

function UserDashboard({ user }: { user: User | null }) {
  const [projects,setProjects]=useState<Project[]>([]); const [creating,setCreating]=useState(false); const [error,setError]=useState(''); const [token,setToken]=useState('');
  useEffect(()=>{ if(!user){window.location.href=href('/login');return;} platformApi.myProjects().then(setProjects).catch(e=>setError(e.message)); },[user]);
  async function create(event:FormEvent<HTMLFormElement>){event.preventDefault();setError('');const values=Object.fromEntries(new FormData(event.currentTarget));try{const project=await platformApi.createProject({slug:String(values.slug),name:String(values.name),description:String(values.description),repository_url:String(values.repository_url),spec_path:String(values.spec_path)});window.location.href=href(`/${project.owner}/${project.slug}`);}catch(e){setError(e instanceof Error?e.message:'Unable to create project');}}
  async function makeToken(){try{setToken((await platformApi.createToken()).token);}catch(e){setError(e instanceof Error?e.message:'Unable to create token');}}
  async function logout(){await platformApi.logout();window.location.href=href('/');}
  return <Layout user={user}><main className="account-page"><div className="account-heading"><div><span className="site-kicker">YOUR WORKSPACE</span><h1>@{user?.username}</h1><p>Every project has its own public specification, releases, implementations, and private operator view.</p></div><div><button className="secondary-cta" onClick={logout}><LogOut size={15}/>Sign out</button><button className="primary-cta" onClick={()=>setCreating(!creating)}><Plus size={16}/>New project</button></div></div>
    {error&&<p className="form-error">{error}</p>}{creating&&<form className="project-form" onSubmit={create}><h2>Create a project</h2><p className="form-help">Start in a public GitHub repository, run <code>polyform init</code>, and push it before connecting it here. <a href={href('/docs/create-project#repository')}>What should the repository contain?</a></p><div className="form-row"><label>Project name<input name="name" required placeholder="Safer ZIP"/></label><label>URL slug<input name="slug" required pattern="[a-z0-9][a-z0-9-]{1,62}[a-z0-9]" placeholder="safer-zip"/></label></div><label>Description<textarea name="description" rows={3} placeholder="What does this software do?"/></label><div className="form-row"><label>Public GitHub repository <a className="field-help" href={href('/docs/create-project#repository')}>Help</a><input name="repository_url" required type="url" pattern="https://github\.com/[^/]+/[^/]+/?" placeholder="https://github.com/you/project"/></label><label>Specification path <small>inside the repository</small><input name="spec_path" required defaultValue="specs/polyform.toml"/><span className="field-hint"><code>polyform init</code> creates this file.</span></label></div><button className="primary-cta">Create project<ArrowRight size={15}/></button></form>}
    <section className="workspace-section"><div><h2>Projects</h2><span>{projects.length} owned by @{user?.username}</span></div>{projects.length?<div className="project-cards">{projects.map(project=><ProjectCard project={project} key={project.id}/>)}</div>:<div className="empty-workspace"><Boxes/><h3>No projects yet</h3><p>Create your first project to publish a specification.</p></div>}</section>
    <section className="token-panel"><div><KeyRound/><h2>CLI access</h2><p>Create a personal token for publishing releases from your machine.</p></div>{token?<div className="token-result"><code>{token}</code><small>Copy this now. It will not be shown again.</small></div>:<button className="secondary-cta" onClick={makeToken}>Create CLI token</button>}</section>
  </main></Layout>;
}

function PublicProject({ owner, slug, user }: { owner:string;slug:string;user:User|null }) {
  const [project,setProject]=useState<Project|null>(null); const [error,setError]=useState(''); const [editing,setEditing]=useState(false); const [saving,setSaving]=useState(false);
  useEffect(()=>{platformApi.project(owner,slug).then(setProject).catch(e=>setError(e.message));},[owner,slug]);
  async function save(event:FormEvent<HTMLFormElement>){event.preventDefault();setSaving(true);setError('');const values=Object.fromEntries(new FormData(event.currentTarget));try{setProject(await platformApi.updateProject(owner,slug,{name:String(values.name),description:String(values.description),repository_url:String(values.repository_url),spec_path:String(values.spec_path)}));setEditing(false);}catch(e){setError(e instanceof Error?e.message:'Unable to update project');}finally{setSaving(false);}}
  if(error)return <Layout user={user}><main className="not-found"><h1>Project not found</h1><p>{error}</p></main></Layout>;
  if(!project)return <Layout user={user}><main className="not-found"><p>Loading project…</p></main></Layout>;
  const latest=project.releases?.[0]; const mine=user?.username===project.owner;
  return <Layout user={user}><main className="project-page"><div className="project-breadcrumb"><a href={href(`/${project.owner}`)}>{project.owner}</a><span>/</span><b>{project.slug}</b><span className="public-badge">PUBLIC</span></div><section className="project-hero"><div><h1>{project.name}</h1><p>{project.description||'An open Polyform software project.'}</p><div className="project-links">{project.repository_url&&<a href={project.repository_url} target="_blank" rel="noreferrer"><Code2 size={15}/>Source</a>}{project.spec_path&&project.repository_url&&<a href={`${project.repository_url}/blob/main/${project.spec_path}`} target="_blank" rel="noreferrer"><BookOpen size={15}/>Specification</a>}{mine&&<a href={href(`/${project.owner}/${project.slug}/dashboard`)}><Activity size={15}/>Telemetry dashboard</a>}{mine&&<button type="button" onClick={()=>setEditing(!editing)}>Edit project</button>}</div></div><div className="release-callout"><span>LATEST RELEASE</span><b>{latest?`v${latest.version}`:'Not published'}</b>{latest?.artifact_url?<a href={latest.artifact_url}><Download size={15}/>Download</a>:<small>Publish with the CLI to create a release.</small>}</div></section>
    {editing&&<form className="project-form project-edit-form" onSubmit={save}><h2>Edit project</h2><label>Project name<input name="name" required defaultValue={project.name}/></label><label>Description<textarea name="description" rows={3} defaultValue={project.description}/></label><div className="form-row"><label>Public GitHub repository <a className="field-help" href={href('/docs/create-project#repository')}>Help</a><input name="repository_url" required type="url" pattern="https://github\.com/[^/]+/[^/]+/?" defaultValue={project.repository_url||''}/></label><label>Specification path <small>inside the repository</small><input name="spec_path" required defaultValue={project.spec_path||'specs/polyform.toml'}/><span className="field-hint"><code>polyform init</code> creates <code>specs/polyform.toml</code>.</span></label></div><div className="form-actions"><button className="primary-cta" disabled={saving}>{saving?'Saving…':'Save changes'}</button><button className="secondary-cta" type="button" onClick={()=>setEditing(false)}>Cancel</button></div></form>}
    <section className="project-stats"><div><b>{project.releases?.length||0}</b><span>releases</span></div><div><b>{project.spec_functions||0}</b><span>spec functions</span></div><div><b>{project.implementations||0}</b><span>implementations</span></div></section>
    <div className="project-columns"><section><div className="section-heading"><span>GET STARTED</span><h2>Install this project</h2></div>{latest?<pre><code>polyform install {project.owner}/{project.slug} --server https://omalled.com/polyform</code></pre>:<div className="project-empty">No installable release yet.</div>}</section><section><div className="section-heading"><span>RELEASES</span><h2>Published history</h2></div>{project.releases?.length?<ol className="release-list">{project.releases.map(release=><li key={release.id}><div><b>v{release.version}</b><span>{release.channel}</span></div><time>{new Date(release.created_at).toLocaleDateString()}</time></li>)}</ol>:<div className="project-empty">The first signed release will appear here.</div>}</section></div>
  </main></Layout>;
}

function PublicUser({ username, user }: { username:string;user:User|null }) {
  const [profile,setProfile]=useState<UserProfile|null>(null); const [error,setError]=useState('');
  useEffect(()=>{platformApi.user(username).then(setProfile).catch(e=>setError(e.message));},[username]);
  if(error)return <Layout user={user}><main className="not-found"><h1>User not found</h1><p>{error}</p></main></Layout>;
  if(!profile)return <Layout user={user}><main className="not-found"><p>Loading profile…</p></main></Layout>;
  return <Layout user={user}><main className="account-page public-profile"><div className="account-heading"><div><span className="site-kicker">OPEN PROJECTS</span><h1>@{profile.username}</h1><p>Open-source Polyform projects from this account.</p></div>{user?.username===profile.username&&<a className="primary-cta" href={href('/dashboard')}>Manage projects<ArrowRight size={15}/></a>}</div><section className="workspace-section"><div><h2>Projects</h2><span>{profile.projects.length} public</span></div>{profile.projects.length?<div className="project-cards">{profile.projects.map(project=><ProjectCard project={project} key={project.id}/>)}</div>:<div className="empty-workspace"><Boxes/><h3>No public projects yet</h3></div>}</section></main></Layout>;
}

export type DocTopic = 'overview'|'install'|'create-project'|'specification'|'generate'|'runtime'|'publish'|'telemetry';

const docNav: Array<[DocTopic,string]> = [
  ['overview','Overview'], ['install','Install the CLI'], ['create-project','Create a project'],
  ['specification','Write a specification'], ['generate','Generate the code'], ['runtime','Connect your app'],
  ['publish','Check and publish'], ['telemetry','Results and quarantine'],
];

function DocLink({ topic, active, children }: { topic:DocTopic;active:DocTopic;children:React.ReactNode }) {
  return <a className={topic===active?'active':''} href={href(topic==='overview'?'/docs':`/docs/${topic}`)}>{children}</a>;
}

export function Docs({ user, topic }: { user:User|null;topic:DocTopic }) {
  return <Layout user={user}><main className="docs-page"><aside><b>Documentation</b>{docNav.map(([key,label])=><DocLink topic={key} active={topic} key={key}>{label}</DocLink>)}</aside><article><DocContent topic={topic} user={user}/><div className="doc-next">{docNav.map(([key,label],index)=>key===topic&&index<docNav.length-1?<a href={href(`/docs/${docNav[index+1][0]}`)} key={key}>Next: {docNav[index+1][1]} <ArrowRight size={15}/></a>:null)}</div></article></main></Layout>;
}

function DocContent({topic,user}:{topic:DocTopic;user:User|null}) {
  if(topic==='install') return <><span className="site-kicker">INSTALL THE CLI</span><h1>Put <code>polyform</code> on your computer</h1><p>The Polyform command prepares your project, starts coding agents, runs your tests, publishes releases, and installs software from public Polyform projects.</p><h2>macOS or Linux</h2><pre><code>curl -fsSL https://omalled.com/polyform/downloads/install.sh | sh</code></pre><p>This installs the binary in <code>~/.local/bin</code>. If your shell cannot find it, add that directory to your <code>PATH</code> and open a new terminal.</p><pre><code>{`export PATH="$HOME/.local/bin:$PATH"\npolyform --version`}</code></pre><h2>Install a coding agent</h2><p><code>polyform generate</code> uses the <code>codex</code> command by default. Install Codex and sign in before generating code, or pass <code>--agent</code> with another agent program that accepts instructions through standard input.</p><h2>Direct downloads</h2><ul><li><a href={href('/downloads/polyform-aarch64-apple-darwin.zip')}>Apple Silicon macOS</a> (signed and notarized, M1 or newer)</li><li><a href={href('/downloads/polyform-x86_64-unknown-linux-gnu')}>x86-64 Linux</a></li><li><a href={href('/downloads/polyform-source.tar.gz')}>Complete open-source code</a></li></ul><h2>What gets installed?</h2><p>One small command-line program. It does not run in the background or send anything until you run a command that needs the Polyform website.</p><div className="doc-note"><b>Language support today</b><span>The specification and generation process can describe any language. The ready-made runtime library and complete example currently use Rust.</span></div></>;

  if(topic==='create-project') return <><span className="site-kicker">CREATE A PROJECT</span><h1>Build your first Polyform project: Fizz Buzz</h1><p>This walkthrough builds a tiny Rust project so you can see the whole idea before applying it to real software. Four small behaviors are specified separately, then coding agents create several interchangeable implementations of each.</p><h2 id="repository">1. Start a normal repository</h2><pre><code>{`mkdir polyform-fizzbuzz\ncd polyform-fizzbuzz\ngit init\ncargo init --bin .\npolyform init`}</code></pre><p><code>polyform init</code> adds <code>polyform.toml</code> and the conventional specification file <code>specs/polyform.toml</code>. For this starter Rust project, the generated configuration already knows to run <code>cargo test</code>; you do not need to configure packaging yet.</p><h2>2. Describe Fizz Buzz in <code>specs/polyform.toml</code></h2><p>Replace the example specification with these four contracts. Divisibility checks, classification, and display are independently swappable, which makes the combinations easy to see.</p><pre><code>{`schema_version = 1\napplication = "polyform-fizzbuzz"\nrelease = "0.1.0"\npurpose = "Print Fizz Buzz for numbers from 1 through 100."\n[[function]]\nname = "is_divisible_by_three"\npurpose = "Decide whether a number is evenly divisible by 3."\nsignature = "fn(u32) -> bool"\ninputs = ["one integer from 1 through 100"]\noutputs = ["true exactly when the input is divisible by 3"]\nerrors = []\nrequirements = ["Return true if and only if dividing the input by 3 leaves no remainder."]\n\n[[function.examples]]\nname = "nine"\ngiven = "the number 9"\nexpect = "true"\n\n[[function.examples]]\nname = "ten"\ngiven = "the number 10"\nexpect = "false"\n\n[[function]]\nname = "is_divisible_by_five"\npurpose = "Decide whether a number is evenly divisible by 5."\nsignature = "fn(u32) -> bool"\ninputs = ["one integer from 1 through 100"]\noutputs = ["true exactly when the input is divisible by 5"]\nerrors = []\nrequirements = ["Return true if and only if dividing the input by 5 leaves no remainder."]\n\n[[function.examples]]\nname = "twenty"\ngiven = "the number 20"\nexpect = "true"\n\n[[function.examples]]\nname = "eighteen"\ngiven = "the number 18"\nexpect = "false"\n\n[[function]]\nname = "classify_number"\npurpose = "Combine the two divisibility results into a Fizz Buzz classification."\nsignature = "fn(u32, bool, bool) -> Classification"\ninputs = ["the original number, divisible-by-3 result, and divisible-by-5 result"]\noutputs = ["FizzBuzz, Fizz, Buzz, or Number"]\nerrors = []\nrequirements = [\n  "Return FizzBuzz when both supplied results are true.",\n  "Return Fizz when only divisible-by-3 is true.",\n  "Return Buzz when only divisible-by-5 is true.",\n  "Otherwise return Number containing the original number.",\n  "Use the supplied results instead of repeating either divisibility test."\n]\n\n[[function.examples]]\nname = "both"\ngiven = "the number 15 with true and true"\nexpect = "FizzBuzz"\n\n[[function.examples]]\nname = "neither"\ngiven = "the number 7 with false and false"\nexpect = "Number containing 7"\n\n[[function]]\nname = "render_line"\npurpose = "Render one classification as user-visible text."\nsignature = "fn(u32, Classification) -> String"\ninputs = ["the original number and its classification"]\noutputs = ["one line without a trailing newline"]\nerrors = []\nrequirements = [\n  "Render FizzBuzz, Fizz, and Buzz exactly with that capitalization.",\n  "Render Number as the base-10 input with no padding."\n]\n\n[[function.examples]]\nname = "buzz"\ngiven = "the number 10 classified as Buzz"\nexpect = "Buzz"\n\n[[function.examples]]\nname = "ordinary number"\ngiven = "the number 7 classified as Number"\nexpect = "7"`}</code></pre><p>This file describes behavior, not an implementation. Every generated version must satisfy the same requirements and examples.</p><h2>3. Have coding agents implement it</h2><pre><code>polyform generate --count 5</code></pre><p>Polyform starts Codex as the default coding agent. One agent first turns the specification into shared conformance tests. Implementation agents then request five independently structured candidates for each of the four functions—twenty candidates in all. Each candidate is accepted only after the project checks pass.</p><div className="doc-note"><b>Five versions of four functions create 625 combinations</b><span>One installation might use the first divisible-by-3 check, the fourth divisible-by-5 check, the second classifier, and the fifth renderer. Another can receive a different mix.</span></div><h2>4. Check what the agents built</h2><pre><code>{`cargo test\npolyform check`}</code></pre><p>Read the generated source and tests too. Passing checks mean the implementations agree with this specification; they do not replace human review. The next documentation pages explain the specification format and generation process in more depth.</p><h2>5. Push the finished source to GitHub</h2><p>Create an empty <b>public</b> repository on GitHub, then push this project:</p><pre><code>{`git add .\ngit commit -m "Build Polyform Fizz Buzz"\ngit branch -M main\ngit remote add origin https://github.com/YOUR-USERNAME/polyform-fizzbuzz.git\ngit push -u origin main`}</code></pre><p>The repository is public so users can inspect the specification, tests, and every implementation.</p><h2>6. Create the project on Polyform</h2><ol><li><a href={user?href('/dashboard'):href('/signup')}>{user?'Open your dashboard':'Create an account'}</a> and choose <b>New project</b>.</li><li>Use your repository URL: <code>https://github.com/YOUR-USERNAME/polyform-fizzbuzz</code>.</li><li>Keep the specification path as <code>specs/polyform.toml</code>.</li><li>Create the project. You can edit these details later from its project page.</li></ol><p>The specification path is simply the location of the file <em>inside the repository</em>. It is not another URL or a path elsewhere on your computer.</p><h2>What comes next?</h2><p>You now have a public project with agent-written implementations that pass one shared contract. Continue to <a href={href('/docs/runtime')}>Connect your app</a> to select different combinations at runtime, then <a href={href('/docs/publish')}>check and publish</a> an installable release.</p></>;

  if(topic==='specification') return <><span className="site-kicker">WRITE A SPECIFICATION</span><h1>Describe the complete behavior before generating code</h1><p>The specification is the public source of truth for both tests and implementations. A reader—or an agent—should be able to build the software from this document without copying behavioral decisions from existing code.</p><h2>Cover the whole design</h2><p>Describe the application’s purpose, outside standards it follows, and every public function that makes up the design. For each function, state its purpose, exact interface, accepted inputs, returned values, allowed errors, security rules, edge cases, and concrete examples. Private helper functions do not belong in the design yet; agents may create those later while implementing it.</p><h2>A complete function example</h2><pre><code>{`schema_version = 1\napplication = "zip-safe"\nrelease = "0.1.0"\npurpose = "List and safely extract supported ZIP archives."\nexternal_references = ["PKWARE APPNOTE 6.3.10, section 4.4.4"]\n[[function]]\nname = "decode_filename"\npurpose = "Decode a ZIP filename without changing its path."\nsignature = "fn(&[u8], u16) -> Result<String, ZipError>"\ninputs = [\n  "raw filename bytes exactly as stored in the archive",\n  "the 16-bit ZIP general-purpose flag field"\n]\noutputs = ["one Unicode string containing the same filename characters"]\nerrors = ["InvalidEncoding"]\nrequirements = [\n  "If flag bit 11 is set, decode with strict UTF-8 and reject every invalid byte sequence.",\n  "If flag bit 11 is clear, map every byte with IBM Code Page 437.",\n  "Preserve slash, backslash, dot, and NUL characters; path safety is handled by another function.",\n  "Do not replace, skip, or guess invalid UTF-8 bytes."\n]\n\n[[function.examples]]\nname = "declared UTF-8"\ngiven = "bytes 63 61 66 c3 a9 2e 74 78 74 and flags 0x0800"\nexpect = "Ok(\\\"café.txt\\\")"\n\n[[function.examples]]\nname = "invalid declared UTF-8"\ngiven = "bytes ff 2e 74 78 74 and flags 0x0800"\nexpect = "Err(InvalidEncoding)"`}</code></pre><h2>What becomes an executable test?</h2><p>The <code>requirements</code> and <code>function.examples</code> entries are part of the specification. They describe behavior; they are not names of test functions. When you run <code>polyform generate</code>, a test-author agent turns them into one shared conformance suite in your repository’s normal test directory. Every generated implementation must pass that same suite.</p><div className="field-list"><b><code>purpose</code></b><span>Why the application or function exists and what responsibility it owns.</span><b><code>signature</code></b><span>The exact interface every implementation must provide.</span><b><code>requirements</code></b><span>Precise rules, including edge cases and security behavior. Avoid unexplained words such as “safe” or “correct.”</span><b><code>function.examples</code></b><span>Concrete inputs and expected results that remove ambiguity and become shared test cases.</span></div><h2>Check completeness before spending agent time</h2><p><code>polyform generate</code> refuses a specification that is missing a purpose, interface, requirements, or behavioral examples. Review the complete document first; generation is the next phase.</p><div className="doc-note"><b>Your job is the behavior, not five copies of the code</b><span>Humans write and review the specification. Coding agents create the conformance tests and implementation volume from that shared authority.</span></div></>;

  if(topic==='generate') return <><span className="site-kicker">GENERATE THE CODE</span><h1>Ask coding agents to build every implementation</h1><p>Once the specification is complete, one command creates the shared tests and multiple independently structured implementations. Codex is the default agent.</p><pre><code>polyform generate --count 5</code></pre><h2>What the command does</h2><ol><li>Validates that every specified function has a purpose, interface, requirements, and behavioral examples.</li><li>Starts a test-author agent to convert the specification into one shared executable conformance suite.</li><li>Starts a separate implementation-agent pass for each requested candidate of each function.</li><li>Prevents those agents from silently changing the specification.</li><li>Runs every command in <code>[[checks]]</code> after each candidate and records whether it was accepted.</li></ol><p>With three specified functions and <code>--count 5</code>, Polyform requests fifteen implementation candidates. Humans review the results; they do not hand-write fifteen functions.</p><h2>How candidates are pushed apart</h2><p>Every implementation request receives a different, deterministic diversity brief. Polyform mixes an algorithmic approach, control-flow shape, data representation, validation strategy, engineering priority, and dependency policy. For five candidates, the major five-way dimensions are balanced so every option is used once.</p><p>The agent is also told not to imitate existing variants. The exact brief is saved beside the result in <code>.polyform/generation.jsonl</code>, so reviewers can compare the requested design with the code that was produced. The behavioral specification and shared tests still take priority over every style direction.</p><h2>Generate one function again</h2><pre><code>polyform generate --function decode_filename --count 2 --skip-test-generation</code></pre><p>This asks for two additional decoder candidates and keeps the existing shared tests. It is useful after you improve one function’s specification or want more diversity.</p><h2>Use another coding agent</h2><pre><code>polyform generate --count 5 --agent /path/to/agent</code></pre><p>The default <code>codex</code> command runs non-interactively with permission to edit only the project workspace. Another agent program can be used if it reads the prompt from standard input, edits the current repository, and exits unsuccessfully when it cannot finish.</p><h2>Review what the agents produced</h2><p>Read the code, confirm that the implementations use genuinely different approaches, and inspect <code>.polyform/generation.jsonl</code>. Polyform will reject failed checks, but passing tests are evidence—not a guarantee that the specification itself is complete.</p></>;

  if(topic==='runtime') return <><span className="site-kicker">CONNECT YOUR APP</span><h1>Use the combination selected for each installation</h1><p>Your application ships as one program containing every accepted implementation. Each installation receives a list telling it which implementation to use for every specified function. You do not build a separate program for every possible combination.</p><h2>1. Add the current Rust runtime</h2><p>Download the <a href={href('/downloads/polyform-source.tar.gz')}>open-source Polyform code</a>, place it beside your project, and add the runtime library as a local dependency:</p><pre><code>{`[dependencies]\npolyform-runtime = { path = "../polyform/crates/polyform-runtime" }`}</code></pre><p>This is ordinary Rust dependency syntax. No separate package-registry account is needed.</p><h2>2. Register this installation</h2><pre><code>{`use polyform_runtime::Client;\n\nlet client = Client::register(\n    "https://omalled.com/polyform",\n    release_id,\n    Some(installation_id),\n    "balanced",\n)?;`}</code></pre><p>Polyform returns one implementation ID for every function in the release.</p><h2>3. Call the selected implementation</h2><pre><code>{`let selected = client.composition.implementations\n    .get("decode_filename")\n    .map(String::as_str)\n    .unwrap_or("decode_filename.strict_utf8");\n\nlet result = match selected {\n    "decode_filename.strict_utf8" => strict_utf8(bytes, flags),\n    "decode_filename.table_driven" => table_driven(bytes, flags),\n    other => return Err(format!("unknown implementation: {other}")),\n};`}</code></pre><p>The generated code adds this registration and dispatch structure. Private helpers remain part of their own implementation and are not selected separately.</p><h2>4. Receive replacements</h2><pre><code>{`if client.refresh()? {\n    // Use the new combination for later calls.\n}`}</code></pre><p>Call <code>refresh</code> between units of work—for example, when the app starts, before a new job, or every few minutes. If you quarantined an implementation, this call gives affected installations a replacement.</p></>;

  if(topic==='publish') return <><span className="site-kicker">CHECK AND PUBLISH</span><h1>Run the final checks and publish a release</h1><p>Tests and compilation run on your computer using the commands in <code>polyform.toml</code>. The Polyform website receives the finished implementation list and release information, not a build job.</p><h2>1. List the accepted implementations</h2><p>Your <code>manifest_command</code> prints a small JSON list like this:</p><pre><code>{`{\n  "application": "zip-safe",\n  "version": "0.1.0",\n  "spec_functions": [\n    {\n      "name": "decode_filename",\n      "implementations": [\n        { "id": "decode_filename.strict_utf8", "name": "Strict UTF-8" },\n        { "id": "decode_filename.table_driven", "name": "Table driven" }\n      ]\n    }\n  ]\n}`}</code></pre><p>The generation agents should register each accepted implementation as they add it. Your script reads that registry and prints the list so the published release matches the program.</p><h2>2. Run checks and build</h2><pre><code>{`polyform check\ncargo build --release`}</code></pre><p><code>polyform check</code> runs every shared test and build command, then records the exact specification and source files that passed. If those files change afterward, Polyform makes you check again before publishing.</p><h2>3. Create a release signing key</h2><pre><code>polyform keygen</code></pre><p>This writes <code>.polyform/signing-key.json</code>. Back it up privately and do not commit it. The signature lets users verify that the downloaded program came from this project.</p><h2>4. Create a CLI token</h2><p>Open <a href={href('/dashboard')}>your dashboard</a>, choose <b>Create CLI token</b>, and copy it. The token is shown once and authorizes publishing to your project.</p><h2>5. Put the program online and publish</h2><pre><code>{`export POLYFORM_TOKEN="pf_…"\npolyform publish \\\n  --project ${user?.username||'you'}/zip-safe \\\n  --server https://omalled.com/polyform \\\n  --artifact-url https://github.com/you/zip-safe/releases/download/v0.1.0/zip-safe`}</code></pre><p>Upload the finished program to a public GitHub Release or another HTTPS download location. Polyform publishes its URL, checksum, signature, specification, and implementation list on your project page.</p><div className="doc-note"><b>Mac downloads may need an Apple signature too</b><span>The Polyform signature proves which project published the file. Apple signing and notarization let macOS verify the developer. A Mac program may need both.</span></div></>;

  if(topic==='telemetry') return <><span className="site-kicker">RESULTS AND QUARANTINE</span><h1>Report outcomes without reporting user data</h1><p>After an operation, report whether it succeeded and which implementations were called. The dashboard uses many installations’ reports to compare code that should behave the same.</p><h2>Report one execution</h2><pre><code>{`use polyform_runtime::CallTelemetry;\n\nlet calls = vec![\n    CallTelemetry::new(\n        "decode_filename",\n        selected,\n        if result.is_ok() { "ok" } else { "error" },\n    ),\n];\n\nclient.report_execution(\n    "extract_archive",\n    result.is_ok(),\n    elapsed_ms,\n    result.as_ref().err().map(|_| "invalid_filename"),\n    &calls,\n)?;`}</code></pre><h2>Send only what comparison needs</h2><ul><li>A random ID for this installation.</li><li>The current list version and implementation IDs being used.</li><li>A short operation name, such as <code>extract_archive</code>.</li><li>Success or failure, duration, and a small error category.</li><li>The specified functions called during that operation and their outcomes.</li></ul><h2>Never send user content</h2><ul><li>No filenames, file contents, database records, prompts, or user documents.</li><li>No full error messages that may contain private values.</li><li>No names, emails, IP addresses, or device fingerprints.</li></ul><h2>What happens when you quarantine an implementation</h2><ol><li>The dashboard compares its failure rate with other implementations of the same function.</li><li>A high relative risk tells you where to investigate; it is not proof by itself.</li><li>Open the linked public source and review the suspicious implementation.</li><li>Choose <b>Quarantine</b> to stop distributing it to new installations immediately.</li><li>Existing installations receive another already-shipped implementation when they next call <code>refresh</code>.</li><li>A new stage appears on the health graph so you can see whether successful executions improve after the change.</li></ol><p><b>Restore</b> makes the implementation available for distribution again. Earlier reports stay attached to the exact code combinations that produced them.</p></>;

  return <><span className="site-kicker">OVERVIEW</span><h1>Build software that does not depend on one implementation</h1><p>Most applications give every user identical code. One hidden bug can therefore affect every installation. Polyform uses coding agents to create several implementations from one complete behavioral specification, then gives installations different combinations of those implementations.</p><h2>The workflow</h2><ol><li><b>Specify the complete behavior.</b> Describe the application, every public function in the design, its interface, rules, errors, and concrete examples.</li><li><b>Generate the code.</b> Run <code>polyform generate --count 5</code>. Codex creates shared conformance tests and five implementation candidates for every function.</li><li><b>Ship one program.</b> The program contains all accepted implementations. Each installation receives a different combination to use.</li><li><b>Compare real outcomes.</b> Applications report success or failure and the implementation IDs involved, without sending user content.</li><li><b>Remove risky code.</b> The dashboard shows implementations that appear unusually often in failures. Quarantine one to stop distributing it and send replacements.</li></ol><h2>A concrete example</h2><p>Imagine a ZIP extractor with five filename decoders and five decompression implementations. One installation might use decoder 2 with decompressor 4. Another might use decoder 5 with decompressor 1. All must follow the same public specification and pass the same tests.</p><p>If decoder 2 contains a rare bug, failures should occur more often where decoder 2 is running. The dashboard links that result to its public source. You can inspect it, quarantine it, and have those installations use another already-shipped decoder.</p><h2>Why multiple implementations help</h2><p>AI makes it practical to create and maintain more code than a human team could write by hand. That extra code creates diversity: a flaw in one approach may not exist in another. As AI-assisted vulnerability discovery makes attacks faster, an independently written alternative may already be available before you have time to design and deploy a traditional patch.</p><div className="doc-note"><b>Humans define what correct means</b><span>Your team owns and reviews the complete specification. Coding agents produce the implementation volume; Polyform tests, distributes, measures, and replaces that code.</span></div></>;
}

export default function Platform() {
  const [user,setUser]=useState<User|null>(null); const [loaded,setLoaded]=useState(false);
  useEffect(()=>{platformApi.me().then(setUser).catch(()=>undefined).finally(()=>setLoaded(true));},[]);
  if(!loaded)return <div className="site-loading"><Brand/></div>;
  const relative=window.location.pathname.startsWith(base)?window.location.pathname.slice(base.length):window.location.pathname;
  const parts=relative.split('/').filter(Boolean);
  if(parts.length===0)return <Landing user={user}/>;
  if(parts[0]==='signup')return <AuthPage mode="signup" onUser={setUser}/>;
  if(parts[0]==='login')return <AuthPage mode="login" onUser={setUser}/>;
  if(parts[0]==='dashboard')return <UserDashboard user={user}/>;
  if(parts[0]==='docs'){
    const requested=(parts[1]||'overview') as DocTopic;
    const topic=docNav.some(([key])=>key===requested)?requested:'overview';
    return <Docs user={user} topic={topic}/>;
  }
  if(parts[0]==='download')return <Docs user={user} topic="install"/>;
  if(parts.length>=3&&parts[2]==='dashboard')return <ProjectDashboard owner={parts[0]} slug={parts[1]} user={user}/>;
  if(parts.length>=2)return <PublicProject owner={parts[0]} slug={parts[1]} user={user}/>;
  if(parts.length===1)return <PublicUser username={parts[0]} user={user}/>;
  return <Layout user={user}><main className="not-found"><h1>Page not found</h1><a href={href('/')}>Return home</a></main></Layout>;
}

function ProjectDashboard({owner,slug,user}:{owner:string;slug:string;user:User|null}) {
  const [project,setProject]=useState<Project|null>(null); const [error,setError]=useState('');
  useEffect(()=>{platformApi.project(owner,slug).then(setProject).catch(e=>setError(e.message));},[owner,slug]);
  if(!user)return <AuthPage mode="login" onUser={()=>window.location.reload()}/>;
  if(error)return <Layout user={user}><main className="not-found"><h1>Dashboard unavailable</h1><p>{error}</p></main></Layout>;
  if(!project)return <div className="site-loading"><Brand/></div>;
  if(user.username!==project.owner)return <Layout user={user}><main className="not-found"><h1>Owner access required</h1></main></Layout>;
  const release=project.releases?.[0];
  if(!release)return <Layout user={user}><main className="not-found"><h1>No published release yet</h1><p>Run <code>polyform publish</code>, then telemetry will appear here.</p><a href={href(`/${owner}/${slug}`)}>Back to project</a></main></Layout>;
  return <ControlRoom releaseId={release.id}/>;
}
