File size: 28,533 Bytes
a8f4b72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import { useEffect, useMemo, useState } from 'react';
import type { FormEvent, ReactNode } from 'react';
import projectCatalog from '../../../configs/projectos.generated.json';

type Project = { name: string; initial: string; tone: string; stage: string; kind: string; description?: string; updated: string; health: string };
type CatalogItem = { name: string; description: string; icon?: string; capabilities: string[] };
type Plan = { id?: string; question: string; project: string; intent?: string; council: string; agents: string[]; model: string; datasets: string; tools: string; logic: string; governance: string; created: string; executionReady?: boolean; governanceGate?: { missingIntegrations: string[]; approvalRequired: boolean } };
type Policy = { id: string; title: string; description: string; status: string; reviewed?: string };
type Snapshot = { id: string; project: string; created: string; state: Project };
type Manifest = { steps: CatalogItem[]; stages: CatalogItem[]; fabrics: CatalogItem[]; agents: CatalogItem[]; councils: CatalogItem[]; governance: CatalogItem[]; knowledge: CatalogItem[] };
type Collection = 'projects' | 'policies' | 'plans' | 'snapshots';
type Modal = { kind: 'new-project' } | { kind: 'project'; project: Project } | { kind: 'stage'; stage: string } | { kind: 'detail'; title: string; description: string; capabilities: string[]; eyebrow: string } | { kind: 'snapshot'; snapshot: Snapshot };

const seedProjects: Project[] = [
  { name: 'Atlas Research', initial: 'A', tone: 'violet', stage: 'Active', kind: 'Research', updated: '12 min ago', health: 'Healthy' },
  { name: 'Northstar Platform', initial: 'N', tone: 'blue', stage: 'Production', kind: 'Platform', updated: '1 hr ago', health: 'Healthy' },
  { name: 'Signal Intelligence', initial: 'S', tone: 'orange', stage: 'Evolving', kind: 'Research', updated: 'Yesterday', health: 'Attention' },
  { name: 'Common Ground', initial: 'C', tone: 'green', stage: 'Active', kind: 'Knowledge', updated: 'Oct 28', health: 'Healthy' }
];
const seedPolicies: Policy[] = [
  { id: 'workspace-access', title: 'Workspace permission defaults', description: 'Proposal to restrict project write access to assigned contributors.', status: 'Pending' },
  { id: 'dataset-trust', title: 'Dataset trust profile updates', description: 'Proposal to require a verified source for new external datasets.', status: 'Pending' }
];
const defaultManifest: Manifest = {
  steps: [], stages: [], fabrics: [], agents: [], councils: [], governance: [], knowledge: []
};
const navItems = [
  ['overview', '◫', 'Overview'], ['projects', '▤', 'Projects'], ['decision', '⌘', 'Decision flow'],
  ['lifecycle', '⟳', 'Lifecycle'], ['fabrics', '◈', 'Fabrics'], ['agents', '♧', 'Agents'],
  ['councils', '◎', 'Councils'], ['governance', '⬡', 'Governance'], ['knowledge', '▧', 'Knowledge']
] as const;

function readLocal<T>(key: Collection, fallback: T): T {
  try { return JSON.parse(localStorage.getItem(`projectos.${key}`) || 'null') ?? fallback; }
  catch { return fallback; }
}
function writeLocal<T>(key: Collection, value: T): void {
  try { localStorage.setItem(`projectos.${key}`, JSON.stringify(value)); } catch { /* Browser storage may be disabled. */ }
}
function collectionRequest(key: Collection, value: unknown): void {
  writeLocal(key, value);
  fetch(`/api/state/${key}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(value) }).catch(() => undefined);
}
function stageTone(stage: string): string {
  if (stage === 'Production') return 'blue';
  if (stage === 'Evolving') return 'orange';
  if (stage === 'Archive' || stage === 'Obsolete') return 'muted';
  return 'green';
}
function localPlan(question: string, project: string): Plan {
  const text = question.toLowerCase();
  const council = /policy|permission|trust|privacy|risk|approval|audit/.test(text) ? 'Governance Council'
    : /deploy|database|docker|runtime|infrastructure|install|server/.test(text) ? 'Infrastructure Council'
      : /design|architecture|system|structure|interface/.test(text) ? 'Architecture Council'
        : /build|implement|code|create|app|feature|fix/.test(text) ? 'Implementation Council'
          : /improv|evol|compare|roadmap|gap|frontier/.test(text) ? 'Evolution Council' : 'Research Council';
  const agents = council === 'Research Council' ? ['Research Agent', 'Knowledge Agent']
    : council === 'Governance Council' ? ['Governance Agent', 'Logic Agent']
      : council === 'Infrastructure Council' ? ['Infrastructure Agent', 'Dependency Agent']
        : council === 'Evolution Council' ? ['Delta Agent', 'Evolution Agent']
          : council === 'Architecture Council' ? ['Logic Agent', 'Infrastructure Agent'] : ['Implementation Agent', 'Logic Agent'];
  return { question, project: project || 'Workspace level', intent: 'local-preview', council, agents, model: 'Not configured', datasets: project ? `${project} project context` : 'No dataset connected', tools: 'No tool adapters configured', logic: 'Draft created; feasibility has not been verified against a runtime.', governance: 'Blocked: execution requires configured providers, policies, and approval.', created: new Date().toISOString(), executionReady: false };
}

export default function App() {
  const [view, setView] = useState('overview');
  const [projects, setProjects] = useState<Project[]>(() => readLocal('projects', seedProjects));
  const [policies, setPolicies] = useState<Policy[]>(() => readLocal('policies', seedPolicies));
  const [plans, setPlans] = useState<Plan[]>(() => readLocal('plans', []));
  const [snapshots, setSnapshots] = useState<Snapshot[]>(() => readLocal('snapshots', []));
  const [manifest, setManifest] = useState<Manifest>(defaultManifest);
  const [modal, setModal] = useState<Modal | null>(null);
  const [plan, setPlan] = useState<Plan | null>(null);
  const [query, setQuery] = useState('');
  const [projectFilter, setProjectFilter] = useState('All');
  const [toast, setToast] = useState('');
  const pendingCount = policies.filter(policy => policy.status === 'Pending').length;

  useEffect(() => {
    let active = true;
    setManifest(projectCatalog as Manifest);
    fetch('/api/state').then(response => response.ok ? response.json() : Promise.reject())
      .then(state => {
        if (!active) return;
        const nextProjects = Array.isArray(state.projects) ? state.projects : readLocal('projects', seedProjects);
        const nextPolicies = Array.isArray(state.policies) ? state.policies : readLocal('policies', seedPolicies);
        const nextPlans = Array.isArray(state.plans) ? state.plans : readLocal('plans', []);
        const nextSnapshots = Array.isArray(state.snapshots) ? state.snapshots : readLocal('snapshots', []);
        setProjects(nextProjects); setPolicies(nextPolicies); setPlans(nextPlans); setSnapshots(nextSnapshots);
        for (const [key, value, remote] of [['projects', nextProjects, state.projects], ['policies', nextPolicies, state.policies], ['plans', nextPlans, state.plans], ['snapshots', nextSnapshots, state.snapshots]] as const) {
          if (Array.isArray(remote)) writeLocal(key, value);
          else collectionRequest(key, value);
        }
      }).catch(() => undefined);
    return () => { active = false; };
  }, []);

  useEffect(() => {
    if (!toast) return;
    const timer = window.setTimeout(() => setToast(''), 2600);
    return () => window.clearTimeout(timer);
  }, [toast]);

  const visibleProjects = useMemo(() => projects.filter(project => project.name.toLowerCase().includes(query.toLowerCase()) && (projectFilter === 'All' || (projectFilter === 'Research' ? project.kind === 'Research' : project.stage === projectFilter))), [projects, projectFilter, query]);
  const saveProjects = (next: Project[]) => { setProjects(next); collectionRequest('projects', next); };
  const savePolicies = (next: Policy[]) => { setPolicies(next); collectionRequest('policies', next); };
  const addProject = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const form = new FormData(event.currentTarget);
    const name = String(form.get('name') || '').trim();
    if (projects.some(project => project.name.toLowerCase() === name.toLowerCase())) { setToast('A project with that name already exists.'); return; }
    const tones = ['violet', 'blue', 'orange', 'green'];
    const project: Project = { name, initial: name[0].toUpperCase(), tone: tones[projects.length % tones.length], stage: 'Research', kind: String(form.get('kind') || '').trim() || 'General', description: String(form.get('description') || '').trim(), updated: 'Just now', health: 'Healthy' };
    saveProjects([project, ...projects]); setModal(null); setView('projects'); setToast(`Project “${name}” created.`);
  };
  const updateProject = (event: FormEvent<HTMLFormElement>, original: Project) => {
    event.preventDefault();
    const form = new FormData(event.currentTarget);
    const next = projects.map(project => project.name === original.name ? { ...project, stage: String(form.get('stage')), kind: String(form.get('kind')).trim() || 'General', updated: 'Just now' } : project);
    saveProjects(next); setModal(null); setToast(`${original.name} updated.`);
  };
  const updateStage = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const form = new FormData(event.currentTarget);
    const name = String(form.get('project'));
    const stage = String(form.get('stage'));
    saveProjects(projects.map(project => project.name === name ? { ...project, stage, updated: 'Just now' } : project));
    setModal(null); setToast(`${name} moved to ${stage}.`);
  };
  const createSnapshot = (project: Project) => {
    const snapshot: Snapshot = { id: globalThis.crypto?.randomUUID?.() || String(Date.now()), project: project.name, created: new Date().toISOString(), state: { ...project } };
    const next = [snapshot, ...snapshots]; setSnapshots(next); collectionRequest('snapshots', next); setModal(null); setToast(`Snapshot saved for ${project.name}.`);
  };
  const reviewPolicy = (policy: Policy, status: string) => {
    savePolicies(policies.map(item => item.id === policy.id ? { ...item, status, reviewed: new Date().toISOString() } : item));
    setToast(`${policy.title}: ${status.toLowerCase()}.`);
  };
  const createPlan = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const form = new FormData(event.currentTarget);
    const question = String(form.get('question') || '').trim();
    const project = String(form.get('project') || '');
    try {
      const response = await fetch('/api/plans/draft', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ question, project }) });
      if (!response.ok) throw new Error('Planner unavailable');
      const result = await response.json() as Plan;
      const next = [result, ...plans.filter(item => item.id !== result.id)].slice(0, 100);
      setPlans(next); writeLocal('plans', next); setPlan(result); setToast('Planning draft created. It has not been executed.');
    } catch {
      const result = localPlan(question, project);
      const next = [result, ...plans].slice(0, 100); setPlans(next); collectionRequest('plans', next); setPlan(result); setToast('Created a browser-only planning draft.');
    }
  };

  const stages = manifest.stages.length ? manifest.stages : ['Research', 'Active', 'Production', 'Evolving', 'Frontier Comparison', 'Delta Analysis', 'Missing Dependencies', 'Evolution Suggestions', 'Obsolete', 'Snapshot', 'Archive', 'Template'].map(name => ({ name, description: '', capabilities: [] }));
  const navTo = (target: string) => { setView(target); setPlan(null); window.scrollTo({ top: 0, behavior: 'smooth' }); };
  const projectRows = (items: Project[]) => items.map(project => <button className="project-row" key={project.name} onClick={() => setModal({ kind: 'project', project })}>
    <span className={`project-mark ${project.tone}`}>{project.initial}</span><span className="project-copy"><strong>{project.name}</strong><small>{project.stage} · Updated {project.updated}</small></span><span className={`stage-pill ${stageTone(project.stage)}`}>{project.stage}</span><span className="arrow">↗</span>
  </button>);
  const catalogCards = (items: CatalogItem[], eyebrow: string) => <div className="card-grid">{items.map(item => <button className="catalog-card" key={item.name} onClick={() => setModal({ kind: 'detail', title: item.name, eyebrow, description: item.description, capabilities: item.capabilities })}>
    <span className="catalog-icon">{item.icon || item.name[0]}</span><strong>{item.name}</strong><p>{item.description}</p><small>View details ↗</small>
  </button>)}</div>;

  let page: ReactNode;
  if (view === 'projects') page = <><PageHeading eyebrow="WORKSPACE / DIRECTORY" title="Projects" description="Manage the full lifecycle of your project workspaces." action={<button className="primary" onClick={() => setModal({ kind: 'new-project' })}>+ New project</button>} /><div className="toolbar"><div className="filters">{['All', 'Research', 'Production', 'Evolving'].map(filter => <button key={filter} className={projectFilter === filter ? 'active-filter' : ''} onClick={() => setProjectFilter(filter)}>{filter === 'All' ? 'All projects' : filter}{filter === 'All' && <b>{projects.length}</b>}</button>)}</div><input value={query} onChange={event => setQuery(event.target.value)} placeholder="Search projects" /></div><section className="panel directory"><div className="directory-head"><span>PROJECT</span><span>STAGE</span><span>UPDATED</span><span></span></div>{visibleProjects.length ? projectRows(visibleProjects) : <p className="empty">No projects match your search.</p>}</section></>;
  else if (view === 'decision') page = <><PageHeading eyebrow="OPERATIONS / DECISION FORMULA" title="From question to canon." description="A governed path from intent to durable project knowledge." /><div className="decision-layout"><section className="panel decision-panel"><div className="panel-head"><div><h2>Plan a question</h2><p>Generate a routing proposal for review.</p></div><span className="draft-label">LOCAL DRAFT</span></div><form className="plan-form" onSubmit={createPlan}><label>Your question<textarea name="question" required maxLength={700} placeholder="What are you trying to learn or build?" /></label><label>Project context<select name="project"><option value="">Workspace level</option>{projects.map(project => <option key={project.name} value={project.name}>{project.name}</option>)}</select></label><button className="primary" type="submit">Generate plan →</button></form></section><aside className="formula-aside"><b>OPERATIONS AGENT</b><h2>Every request starts with intent.</h2><p>The local planner drafts intent, council, and specialist assignments. It does not execute actions.</p><div className="aside-count"><strong>{manifest.steps.length || 15}</strong><span>decision stages</span></div><div className="aside-count"><strong>2</strong><span>validation gates</span></div></aside></div><div className="formula-list">{manifest.steps.map((step, index) => <button className={`formula-step ${step.name.includes('Governance') || step.name.includes('Logic') ? 'gate' : ''}`} key={`${step.name}-${index}`} onClick={() => setModal({ kind: 'detail', title: step.name, eyebrow: `DECISION STAGE ${String(index + 1).padStart(2, '0')}`, description: step.description, capabilities: [] })}><span>{String(index + 1).padStart(2, '0')}</span><div><strong>{step.name}</strong><small>{step.description}</small></div><i>↗</i></button>)}</div>{plan && <PlanCard plan={plan} />}{plans.length > 0 && <section className="panel history"><h2>Recent planning drafts</h2>{plans.slice(0, 5).map((item, index) => <button key={`${item.id || item.created}-${index}`} onClick={() => setPlan(item)}><strong>{item.question}</strong><small>{item.council} · {new Date(item.created).toLocaleString()}</small><span>Open draft →</span></button>)}</section>}</>;
  else if (view === 'lifecycle') page = <><PageHeading eyebrow="PROJECTS / LIFECYCLE" title="Built to keep evolving." description="Move projects through research, delivery, and continuous improvement." action={<button className="secondary" onClick={() => setModal({ kind: 'stage', stage: 'Active' })}>Update a project stage</button>} /><div className="lifecycle-grid">{stages.map((stage, index) => <button key={stage.name} className="lifecycle-card" onClick={() => setModal({ kind: 'detail', title: stage.name, eyebrow: `LIFECYCLE STAGE ${String(index + 1).padStart(2, '0')}`, description: stage.description, capabilities: [] })}><small>STAGE {String(index + 1).padStart(2, '0')}</small><strong>{stage.name}</strong><p>{stage.description}</p></button>)}</div></>;
  else if (view === 'fabrics') page = <><PageHeading eyebrow="SYSTEMS / FABRICS" title="Connected by design." description="Fabric names and functions are loaded from the XML manifest." />{catalogCards(manifest.fabrics, 'FABRIC SUBSYSTEM')}</>;
  else if (view === 'agents') page = <><PageHeading eyebrow="SYSTEMS / AGENT POOL" title="Specialists, one system." description="Agent descriptions are loaded from the XML manifest." />{catalogCards(manifest.agents, 'SPECIALIST AGENT')}</>;
  else if (view === 'councils') page = <><PageHeading eyebrow="SYSTEMS / COUNCIL ENGINE" title="Better decisions together." description="Council templates bring the right specialists together for each kind of work." />{catalogCards(manifest.councils, 'COUNCIL TEMPLATE')}</>;
  else if (view === 'governance') page = <><PageHeading eyebrow="SYSTEMS / GOVERNANCE" title="Trust with clear boundaries." description="Sample review decisions are stored in SQLite when the API is running." /><section className="panel policy-panel"><div className="panel-head"><div><h2>Review queue</h2><p>{pendingCount} sample proposals pending</p></div><span className="draft-label">LOCAL DEMO</span></div>{policies.map(policy => <div className="policy-row" key={policy.id}><div><strong>{policy.title}</strong><p>{policy.description}</p></div><span className={`policy-state ${policy.status === 'Pending' ? 'pending' : 'done'}`}>{policy.status}</span>{policy.status === 'Pending' && <div className="policy-actions"><button onClick={() => reviewPolicy(policy, 'Approved')}>Approve</button><button onClick={() => reviewPolicy(policy, 'Declined')}>Decline</button></div>}</div>)}</section>{catalogCards(manifest.governance, 'GOVERNANCE CONTROL')}</>;
  else if (view === 'knowledge') page = <><PageHeading eyebrow="SYSTEMS / KNOWLEDGE FABRIC" title="Keep what you learn." description="Create and review project-state snapshots." /><section className="panel snapshot-panel"><div className="panel-head"><div><h2>Project snapshots</h2><p>State records stored locally</p></div><span className="draft-label">{snapshots.length} SAVED</span></div>{snapshots.length ? snapshots.map(snapshot => <button key={snapshot.id} className="snapshot-row" onClick={() => setModal({ kind: 'snapshot', snapshot })}><span>◷</span><div><strong>{snapshot.project}</strong><small>{new Date(snapshot.created).toLocaleString()} · {snapshot.state.stage}</small></div><i>↗</i></button>) : <p className="empty">No snapshots yet. Open a project and create one to preserve its state.</p>}</section><div className="knowledge-flow">{catalogCards(manifest.knowledge, 'KNOWLEDGE AREA')}</div></>;
  else page = <><PageHeading eyebrow="SATURDAY, OCTOBER 31, 2026 / LOCAL PROTOTYPE" title="Good morning, Workspace." description="Explore the ProjectOS workflow. Sample records are illustrative; your changes persist locally." action={<button className="primary" onClick={() => setModal({ kind: 'new-project' })}>+ New project</button>} /><div className="stat-grid"><button onClick={() => navTo('projects')}><small>SAMPLE PROJECTS</small><strong>{String(projects.length).padStart(2, '0')}</strong><span>Saved locally when edited</span></button><button onClick={() => navTo('agents')}><small>AGENTS DEFINED</small><strong>{String(manifest.agents.length || 12).padStart(2, '0')}</strong><span>Listed in the architecture</span></button><button onClick={() => navTo('governance')}><small>EXAMPLE REVIEWS</small><strong>{String(pendingCount).padStart(2, '0')}</strong><span>Sample proposals</span></button><button onClick={() => navTo('knowledge')}><small>PROJECT SNAPSHOTS</small><strong>{String(snapshots.length).padStart(2, '0')}</strong><span>Saved state records</span></button></div><div className="section-title"><div><h2>Workspace preview</h2><p>Illustrative project records for exploring the workflow.</p></div><button className="link-button" onClick={() => navTo('projects')}>View projects →</button></div><div className="home-grid"><section className="panel recent-projects"><div className="panel-head"><div><h2>Recent projects</h2><p>Project records saved in this browser or local database.</p></div></div>{projectRows(projects.slice(0, 4))}</section><section className="panel flow-preview"><div className="panel-head"><div><h2>Decision flow</h2><p>Question to canonical knowledge</p></div><span className="draft-label">READY TO PLAN</span></div>{manifest.steps.slice(0, 6).map((step, index) => <div className="mini-step" key={step.name}><span>{String(index + 1).padStart(2, '0')}</span>{step.name}</div>)}<button className="link-button" onClick={() => navTo('decision')}>Plan a question →</button></section></div><div className="section-title"><div><h2>Architecture coverage</h2><p>Subsystems represented in this monorepo.</p></div></div><div className="health-grid">{[['Fabrics', manifest.fabrics.length, 'fabrics'], ['Agent pool', manifest.agents.length, 'agents'], ['Council engine', manifest.councils.length, 'councils'], ['Governance', pendingCount, 'governance']].map(([name, count, target]) => <button key={String(name)} onClick={() => navTo(String(target))}><strong>{String(name)}</strong><small>{String(count)} listed</small><span>Open →</span></button>)}</div></>;

  return <div className="app-shell">
    <aside className="sidebar"><a className="brand" onClick={() => navTo('overview')}><span className="brand-mark">P</span><span>project<span>os</span><small>OPERATIONS CONSOLE</small></span></a><div className="nav-label">WORKSPACE</div><nav>{navItems.map(([key, icon, label]) => <button key={key} className={`nav-item ${view === key ? 'active' : ''}`} onClick={() => navTo(key)}><span>{icon}</span>{label}{key === 'projects' && <b>{projects.length}</b>}{key === 'governance' && pendingCount > 0 && <b>{pendingCount}</b>}</button>)}</nav><div className="sidebar-footer"><span className="status-dot" /><div><strong>Local monorepo</strong><small>API and SQLite storage</small></div></div></aside>
    <main className="main"><header className="topbar"><div>Workspace <span>/</span> <strong>{navItems.find(item => item[0] === view)?.[2]}</strong></div><span className="local-label"><i /> Local prototype</span></header><div className="page">{page}</div></main>
    {modal && <div className="overlay" role="presentation" onMouseDown={event => { if (event.target === event.currentTarget) setModal(null); }}><section className="modal" role="dialog" aria-modal="true" aria-labelledby="modal-title"><button className="modal-close" onClick={() => setModal(null)} aria-label="Close">×</button>
      {modal.kind === 'new-project' && <><small className="eyebrow">PROJECTS / CREATE</small><h2 id="modal-title">Start a project</h2><p className="modal-lead">Create a local project record and add context for the next planning run.</p><form className="modal-form" onSubmit={addProject}><label>Project name<input name="name" required maxLength={70} placeholder="For example, Atlas Research" /></label><label>Project type<input name="kind" maxLength={50} placeholder="Research, platform, knowledge…" /></label><label>Description<textarea name="description" maxLength={300} placeholder="What outcome should this project support?" /></label><div className="modal-actions"><button type="button" className="secondary" onClick={() => setModal(null)}>Cancel</button><button className="primary">Create project</button></div></form></>}
      {modal.kind === 'project' && <><small className="eyebrow">PROJECT WORKSPACE</small><h2 id="modal-title">{modal.project.name}</h2><p className="modal-lead">{modal.project.description || `${modal.project.kind} workspace. Project records are stored locally.`}</p><form className="modal-form" onSubmit={event => updateProject(event, modal.project)}><label>Lifecycle stage<select name="stage" defaultValue={modal.project.stage}>{stages.map(stage => <option key={stage.name}>{stage.name}</option>)}</select></label><label>Project type<input name="kind" defaultValue={modal.project.kind} maxLength={50} /></label><p className="notice">Moving to Archive or Template records that stage; it does not delete the project.</p><div className="modal-actions spread"><button type="button" className="secondary" onClick={() => createSnapshot(modal.project)}>Create snapshot</button><span /><button type="button" className="secondary" onClick={() => setModal(null)}>Cancel</button><button className="primary">Save project</button></div></form></>}
      {modal.kind === 'stage' && <><small className="eyebrow">PROJECT LIFECYCLE / UPDATE</small><h2 id="modal-title">Move a project to a new stage</h2><p className="modal-lead">Lifecycle changes are saved to the project record.</p><form className="modal-form" onSubmit={updateStage}><label>Project<select name="project" required>{projects.map(project => <option key={project.name} value={project.name}>{project.name} · {project.stage}</option>)}</select></label><label>New stage<select name="stage" defaultValue={modal.stage}>{stages.map(stage => <option key={stage.name}>{stage.name}</option>)}</select></label><div className="modal-actions"><button type="button" className="secondary" onClick={() => setModal(null)}>Cancel</button><button className="primary">Update stage</button></div></form></>}
      {modal.kind === 'detail' && <><small className="eyebrow">{modal.eyebrow}</small><h2 id="modal-title">{modal.title}</h2><p className="modal-lead">{modal.description}</p>{modal.capabilities.length > 0 && <div className="modal-section"><h3>{modal.eyebrow.includes('COUNCIL') ? 'Council members' : 'Responsibilities and capabilities'}</h3><div className="capability-grid">{modal.capabilities.map(capability => <span key={capability}>{capability}</span>)}</div></div>}<div className="notice">Architecture descriptions come from generated ProjectOS configuration. Live provider integrations depend on configured services and credentials.</div><div className="modal-actions"><button className="primary" onClick={() => setModal(null)}>Done</button></div></>}
      {modal.kind === 'snapshot' && <><small className="eyebrow">PROJECT SNAPSHOT / {new Date(modal.snapshot.created).toLocaleString()}</small><h2 id="modal-title">{modal.snapshot.project}</h2><p className="modal-lead">Saved state: {modal.snapshot.state.stage} · {modal.snapshot.state.kind}</p><div className="notice">This snapshot preserves the project record. It does not yet capture project files or external service state.</div><div className="modal-actions"><button className="primary" onClick={() => setModal(null)}>Done</button></div></>}
    </section></div>}
    {toast && <div className="toast" role="status">{toast}</div>}
  </div>;
}

function PageHeading({ eyebrow, title, description, action }: { eyebrow: string; title: string; description: string; action?: ReactNode }) {
  return <div className="page-heading"><div><small className="eyebrow">{eyebrow}</small><h1>{title}</h1><p>{description}</p></div>{action}</div>;
}

function PlanCard({ plan }: { plan: Plan }) {
  return <section className="panel plan-card"><small className="eyebrow">PLANNING PREVIEW / NOT EXECUTED</small><h2>{plan.question}</h2><p>{plan.project} · {plan.intent || 'suggested'} · {plan.council}</p><div className="plan-grid">{[['SPECIALISTS', plan.agents.join(', ')], ['MODEL', plan.model], ['DATASETS', plan.datasets], ['TOOLS', plan.tools], ['LOGIC GATE', plan.logic], ['GOVERNANCE GATE', plan.governance]].map(([label, value]) => <div key={label}><small>{label}</small><strong>{value}</strong></div>)}</div>{plan.governanceGate?.missingIntegrations.length ? <div className="notice">Missing integrations: {plan.governanceGate.missingIntegrations.join(', ')}. Approval required: {String(plan.governanceGate.approvalRequired)}.</div> : null}</section>;
}