File size: 40,146 Bytes
5bd4e3a | 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 | let decisionSteps = [
['Question','Capture the request'],['Operations Agent','Coordinate the response'],['Determine intent','Classify the desired outcome'],['Choose council template','Select the specialist group'],['Assign models','Route the right model capability'],['Assign datasets','Connect trusted context'],['Assign tools','Select approved tools'],['Assign workspace','Choose the project environment'],['Validate through logic','Check feasibility and consistency'],['Validate through governance','Check policy, trust, and approval',true],['Execute','Run the approved plan'],['Store knowledge','Record useful outcomes'],['Snapshot','Preserve the execution state'],['Consolidate','Resolve and organize knowledge'],['Update canon','Publish durable project truth']
];
let lifecycle = [
['01','Research','Discover the problem and evidence'],['02','Active','Coordinate work and decisions'],['03','Production','Deliver stable project outcomes'],['04','Evolving','Improve capabilities continuously'],['05','Frontier comparison','Compare current and emerging state'],['06','Delta analysis','Identify gaps and opportunities'],['07','Missing dependencies','Surface unavailable requirements'],['08','Evolution suggestions','Propose the next improvements'],['09','Obsolete','Mark work ready for retirement'],['10','Snapshot','Preserve a durable project state'],['11','Archive','Store the completed project'],['12','Template','Make proven patterns reusable']
];
const seedProjects = [
{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'}
];
function readStore(key,fallback){try{const value=JSON.parse(localStorage.getItem(key));return value??fallback}catch{return fallback}}
const apiKeys={'projectos.projects':'projects','projectos.policies':'policies','projectos.plans':'plans','projectos.snapshots':'snapshots'};
function writeStore(key,value){try{localStorage.setItem(key,JSON.stringify(value))}catch{};const collection=apiKeys[key];if(collection&&location.protocol==='http:'&&['localhost','127.0.0.1'].includes(location.hostname)){fetch(`/api/state/${collection}`,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(value)}).catch(()=>{})}return true}
let projects=readStore('projectos.projects',seedProjects);
let fabrics = [
['Identity','Ownership, roles, and enterprise identity providers.','◉'],['Trust','Source, dataset, and model verification with trust scores.','⬡'],['Research','Research connectors for web, papers, docs, and knowledge bases.','⌕'],['Knowledge','Memory, research, lessons, canon, frontier, and archives.','▧'],['Logic','Planning, validation, consensus, contradictions, and intent.','⌘'],['Delta','State comparison, gap analysis, evolution, and obsolescence.','Δ'],['Dependency','Find missing tools, models, permissions, libraries, and data.','⛓'],['Governance','Policies, approvals, trust checks, overrides, and audit.','⬡'],['Execution','Route approved work to PowerShell, Python, Node, Docker, Git, or MCP.','▶'],['Storage','Local SQLite and enterprise PostgreSQL with snapshots.','▤'],['Canvas','Whiteboards, diagrams, and knowledge views.','▱']
];
let agents = ['Research Agent','ML Agent','Logic Agent','Knowledge Agent','Dependency Agent','Delta Agent','Evolution Agent','Infrastructure Agent','Tool Execution Agent','Governance Agent','Canonicalization Agent','Implementation Agent'];
let councils = [['Research Council','Evidence gathering, source review, and discovery.'],['Architecture Council','System boundaries, interfaces, and technical direction.'],['Implementation Council','Code changes, integration, and delivery planning.'],['Infrastructure Council','Environments, runtime, storage, and deployment.'],['Evolution Council','Frontier comparison and continuous improvement.'],['Governance Council','Policy, trust, risk, and approval decisions.']];
let governance = [['Policy Engine','Evaluate plans against the active policy registry.'],['Approval Engine','Route gated actions to the right reviewer.'],['Trust Validation','Check identity, sources, datasets, and models.'],['Override Engine','Record scoped exceptions with justification.'],['Audit Log','Keep an attributable record of decisions and actions.'],['Policy Registry','Maintain versioned rules for the workspace.']];
let knowledge = [['Project memory','Working context and decisions'],['Research','Sources, findings, and evidence'],['Lessons','Reusable outcomes and reflections'],['Canon','The current trusted project record'],['Frontier','Emerging ideas and state of the art'],['Snapshots','Point in time project state'],['Archive','Preserved retired work']];
const seedPolicies=[{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 $ = (q, root=document) => root.querySelector(q);
const $$ = (q, root=document) => [...root.querySelectorAll(q)];
const esc = s => String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
const stageClass = s => s==='Production'?'status-prod':s==='Evolving'?'status-evolve':'status-active';
const initials = p => `<span class="project-symbol sym-${p.tone}">${esc(p.initial||p.name?.[0]||'?')}</span>`;
const projectStatus = p => `<span class="project-status ${stageClass(p.stage)}"><i></i> ${p.stage}</span>`;
const catalogDetails={
fabrics:{
Identity:['Resolves who is acting, what they own, and what roles apply.','Ownership graph','Role registry','LDAP / Entra / OAuth / SAML connectors','Identity is a placeholder until an identity provider is configured.'],
Trust:['Evaluates whether sources, datasets, and models meet workspace trust requirements.','Source verification','Dataset and model verification','Trust scores','No external attestation provider is connected yet.'],
Research:['Connects research sources and organizes evidence for project decisions.','Web and paper discovery','Documentation connectors','Research source attribution','Configure endpoints and credentials to enable connectors.'],
Knowledge:['Organizes project memory into research, lessons, canon, frontier, and archive.','Project memory','Canonical knowledge','Snapshots and archive','Prototype content is stored locally in this browser.'],
Logic:['Builds plans and checks feasibility, consistency, and competing claims.','Intent analysis','Planning and validation','Consensus and contradictions','Decision planning currently runs as a local illustrative preview.'],
Delta:['Compares current and target states to identify gaps and useful evolution.','Current and frontier state','Gap analysis','Evolution and obsolescence','State comparison needs configured repositories.'],
Dependency:['Finds unmet runtime, access, model, tool, library, and dataset requirements.','Missing permissions','Missing tools and models','Missing libraries, datasets, infrastructure','Dependency checks need environment and provider probes.'],
Governance:['Applies policy gates, approval decisions, overrides, and audit recording.','Policy registry','Approval queue','Audit history','The local review queue is persistent; real action enforcement needs a runtime service.'],
Execution:['Dispatches approved work to the appropriate execution adapter.','PowerShell / Python / Node','Docker and Git','MCP tools','This dashboard does not execute commands.'],
Storage:['Defines local and enterprise storage options for project artifacts and vectors.','SQLite and sqlite-vec','PostgreSQL and pgvector','Snapshots, consolidation, archives','This prototype currently uses browser localStorage.'],
Canvas:['Provides visual workspaces for diagrams, whiteboards, and knowledge views.','Whiteboard canvas','Diagram engine','Knowledge views','Canvas workspaces are planned surfaces, not connected editors yet.']
},
agents:{'Research Agent':'Finds evidence and records sources relevant to a question.','ML Agent':'Reviews model choices, evaluation needs, and model-specific constraints.','Logic Agent':'Checks plans for feasibility, consistency, and contradictions.','Knowledge Agent':'Retrieves and organizes project memory and research.','Dependency Agent':'Identifies missing tools, permissions, libraries, data, or infrastructure.','Delta Agent':'Compares current project state with a target or frontier.','Evolution Agent':'Turns comparison results into sequenced improvement suggestions.','Infrastructure Agent':'Plans runtime, storage, and environment requirements.','Tool Execution Agent':'Coordinates approved tool calls through configured adapters.','Governance Agent':'Applies policy checks and identifies human approval needs.','Canonicalization Agent':'Turns verified outcomes into structured, reusable canon.','Implementation Agent':'Plans approved implementation work.'},
councils:{'Research Council':['Combines research and knowledge specialists to answer evidence questions.','Research Agent','Knowledge Agent','Trust review'],'Architecture Council':['Reviews boundaries, dependencies, and system-level trade-offs.','Logic Agent','Dependency Agent','Infrastructure Agent'],'Implementation Council':['Coordinates implementation from an approved plan through a reviewable change.','Implementation Agent','Logic Agent','Tool Execution Agent'],'Infrastructure Council':['Checks environments, storage, runtime, and deployment dependencies.','Infrastructure Agent','Dependency Agent','Governance Agent'],'Evolution Council':['Compares project state with the frontier and ranks improvement opportunities.','Delta Agent','Evolution Agent','Knowledge Agent'],'Governance Council':['Reviews policies, trust, approvals, and recorded exceptions.','Governance Agent','Trust validation','Approval engine']},
governance:Object.fromEntries(governance.map(x=>[x[0],[x[1],'Policy scope and version','Decision rationale','Review and audit record']])),
knowledge:Object.fromEntries(knowledge.map(x=>[x[0],[x[1],'Project and source metadata','Validated updates','History and provenance']]))
};
let decisionGuidance=[
'A person or connected system submits a question or requested outcome.','The Operations Agent coordinates intent analysis, routing, validation, and execution planning.','Classify whether the request is research, implementation, infrastructure, evolution, or governance work.','Choose a council template that brings the relevant specialists into the decision.','Select model providers and capabilities that match the task and trust requirements.','Attach project knowledge and datasets with source and permission context.','Select tools required by the plan, with each tool subject to policy and permission checks.','Bind the plan to the project workspace and runtime boundaries.','Check feasibility, consistency, assumptions, and contradictions before action.','Check trust, policies, permissions, and approval requirements before action.','Run only actions that are available, authorized, and within the configured runtime.','Record useful evidence, decisions, and outcomes with provenance.','Capture the project state needed to reproduce or review the work.','Merge compatible learning into organized project knowledge.','Update the canonical project record with reviewed, durable findings.'
];
$('#flow-mini').innerHTML = decisionSteps.slice(0,6).map((s,i)=>`<div class="mini-step"><span class="step-n">${String(i+1).padStart(2,'0')}</span>${s[0]}</div>`).join('');
$('#formula-list').innerHTML = decisionSteps.map((s,i)=>`<button class="formula-step ${s[2]?'gate':''}" data-step="${i}"><span class="formula-num">${String(i+1).padStart(2,'0')}</span><div><strong>${s[0]}</strong><small>${s[1]}</small></div></button>`).join('');
$('#lifecycle-board').innerHTML = lifecycle.map((s,i)=>`<button class="life-card ${[2,3,7,9,11].includes(i)?'highlight':''}" data-stage="${i}"><span class="life-num">STAGE ${s[0]}</span><strong>${s[1]}</strong><small>${s[2]}</small></button>`).join('');
function infoCards(selector,items,icon,category){$(selector).innerHTML=items.map((item,i)=>{const name=Array.isArray(item)?item[0]:item;const desc=Array.isArray(item)?item[1]:'Specialist available in the local agent pool.';return `<button class="info-card" data-category="${category}" data-index="${i}"><span class="card-symbol">${Array.isArray(item)?item[2]||icon:name[0]}</span><strong>${esc(name)}</strong><p>${esc(desc)}</p><span class="card-open-label">View details ↗</span></button>`}).join('')}
infoCards('#fabric-grid',fabrics,'◈','fabrics'); infoCards('#agent-grid',agents,'♧','agents'); infoCards('#council-grid',councils,'◎','councils'); infoCards('#governance-grid',governance,'⬡','governance'); infoCards('#knowledge-grid',knowledge,'▧','knowledge');
function renderKnowledgePipeline(){const selected=['Project memory','Research','Lessons','Canon','Snapshots'];const icons=['◉','⌕','✦','▧','◷'];$('#knowledge-pipeline').innerHTML=selected.map((name,i)=>{const index=knowledge.findIndex(x=>x[0].toLowerCase()===name.toLowerCase());if(index<0)return '';return `${i?'<span class="pipeline-arrow">→</span>':''}<button class="pipeline-step" data-category="knowledge" data-index="${index}"><span>${icons[i]}</span>${esc(name.replace(/^Project /,''))}</button>`}).join('')}
renderKnowledgePipeline();
function renderProjectList(){ $('#project-list').innerHTML=projects.slice(0,4).map(p=>`<button class="project-row" data-project="${esc(p.name)}">${initials(p)}<span class="project-info"><strong>${esc(p.name)}</strong><small>${esc(p.stage)} · Updated ${esc(p.updated)}</small></span>${projectStatus(p)}<span class="row-arrow">↗</span></button>`).join('')||'<p class="empty-note">No projects yet. Create one to get started.</p>' }
function renderDirectory(query=''){const selected=$('.active-filter')?.textContent.trim().split(' ')[0]||'All';$('#project-directory').innerHTML=projects.filter(p=>p.name.toLowerCase().includes(query.toLowerCase())&&(selected==='All'||p.stage===selected||p.kind===selected)).map(p=>`<button class="directory-row" data-project="${esc(p.name)}"><div class="directory-project">${initials(p)}<span><strong>${esc(p.name)}</strong><small>${esc(p.kind)} workspace</small></span></div>${projectStatus(p)}<span>${esc(p.updated)}</span><span style="color:${p.health==='Healthy'?'#4f9b73':'#c88c40'}">● ${esc(p.health)}</span><span>↗</span></button>`).join('')||'<div class="directory-row">No projects match your search.</div>'}
function persistProjects(){writeStore('projectos.projects',projects);renderDirectory($('#project-search')?.value||'');renderProjectList();updateOverviewStats()}
function renderPlanHistory(){const plans=readStore('projectos.plans',[]);$('#plan-history').innerHTML=plans.length?`<h3 class="history-title">Recent planning runs</h3>${plans.slice(0,5).map((p,i)=>`<div class="history-entry"><span>⌘</span><div><strong>${esc(p.question)}</strong><small>${esc(p.council)} · ${new Date(p.created).toLocaleString()}</small></div><button data-plan="${i}">View plan</button></div>`).join('')}`:''}
function renderPolicyQueue(){const items=readStore('projectos.policies',seedPolicies);const pending=items.filter(x=>x.status==='Pending').length;$('#policy-count').textContent=pending?`${pending} sample proposal${pending===1?'':'s'} need review`:'No sample proposals pending';$('#policy-queue').innerHTML=`<div class="panel-head"><div><h3>Review queue</h3><p>Decisions are saved in this browser and local database when running the API.</p></div><span class="detail-chip">${pending} pending</span></div>${items.length?items.map(item=>`<article class="policy-item"><div><strong>${esc(item.title)}</strong><p>${esc(item.description)}</p></div><span class="policy-state ${item.status==='Pending'?'pending':'resolved'}">${esc(item.status)}</span>${item.status==='Pending'?`<span class="governance-action"><button class="approve" data-policy="${esc(item.id)}" data-decision="Approved">Approve</button><button data-policy="${esc(item.id)}" data-decision="Declined">Decline</button></span>`:''}</article>`).join(''):'<p class="empty-note">No policy proposals. The review queue is clear.</p>'}`}
function applyGeneratedManifest(data){
const capabilityMap=items=>Object.fromEntries((items||[]).map(item=>[item.name,[item.description||'Defined in generated ProjectOS configuration.',...(item.capabilities||[])]]));
decisionGuidance=(data.steps||[]).map(item=>item.description||'Defined in generated ProjectOS configuration.');
decisionSteps=(data.steps||[]).map((item,i)=>[item.name||`Step ${i+1}`,item.description||'Configured in generated settings',Boolean(item.gate)]);
lifecycle=(data.stages||[]).map((item,i)=>[String(i+1).padStart(2,'0'),item.name||`Stage ${i+1}`,item.description||'Defined in generated ProjectOS configuration.']);
fabrics=(data.fabrics||[]).map(item=>[item.name,item.description||'',item.icon||'◈']);catalogDetails.fabrics=capabilityMap(data.fabrics);
agents=(data.agents||[]).map(item=>item.name);catalogDetails.agents=capabilityMap(data.agents);
councils=(data.councils||[]).map(item=>[item.name,item.description||'',item.icon||'◎']);catalogDetails.councils=capabilityMap(data.councils);
governance=(data.governance||[]).map(item=>[item.name,item.description||'',item.icon||'⬡']);catalogDetails.governance=capabilityMap(data.governance);
knowledge=(data.knowledge||[]).map(item=>[item.name,item.description||'',item.icon||'▧']);catalogDetails.knowledge=capabilityMap(data.knowledge);
$('#flow-mini').innerHTML=decisionSteps.slice(0,6).map((s,i)=>`<div class="mini-step"><span class="step-n">${String(i+1).padStart(2,'0')}</span>${esc(s[0])}</div>`).join('');
$('#formula-list').innerHTML=decisionSteps.map((s,i)=>`<button class="formula-step ${s[2]?'gate':''}" data-step="${i}"><span class="formula-num">${String(i+1).padStart(2,'0')}</span><div><strong>${esc(s[0])}</strong><small>${esc(s[1])}</small></div></button>`).join('');
$('#lifecycle-board').innerHTML=lifecycle.map((s,i)=>`<button class="life-card ${[2,3,7,9,11].includes(i)?'highlight':''}" data-stage="${i}"><span class="life-num">STAGE ${esc(s[0])}</span><strong>${esc(s[1])}</strong><small>${esc(s[2])}</small></button>`).join('');
infoCards('#fabric-grid',fabrics,'◈','fabrics');infoCards('#agent-grid',agents,'♧','agents');infoCards('#council-grid',councils,'◎','councils');infoCards('#governance-grid',governance,'⬡','governance');infoCards('#knowledge-grid',knowledge,'▧','knowledge');renderKnowledgePipeline();
}
async function loadGeneratedConfig(){if(location.protocol!=='http:'||!['localhost','127.0.0.1'].includes(location.hostname))return;const response=await fetch('./configs/projectos.generated.json',{cache:'no-store'});if(!response.ok)throw new Error('Generated ProjectOS configuration not available');applyGeneratedManifest(await response.json())}function updateOverviewStats(){const count=projects.filter(p=>!['Archive','Template','Obsolete'].includes(p.stage)).length;const projectStat=$('.stat-grid .stat-card .stat-number');if(projectStat)projectStat.textContent=String(count).padStart(2,'0');const pending=readStore('projectos.policies',seedPolicies).filter(x=>x.status==='Pending').length;const governanceStat=$$('.stat-grid .stat-card .stat-number')[2];if(governanceStat)governanceStat.textContent=String(pending).padStart(2,'0');const snapshotCount=$('#snapshot-count');if(snapshotCount)snapshotCount.textContent=String(readStore('projectos.snapshots',[]).length).padStart(2,'0')}
function renderSnapshots(){const snapshots=readStore('projectos.snapshots',[]);$('#snapshot-list').innerHTML=`<div class="panel-head"><div><h3>Project snapshots</h3><p>Saved state records stored locally.</p></div><span class="detail-chip">${snapshots.length} total</span></div>${snapshots.length?snapshots.slice(0,8).map(s=>`<button class="snapshot-row" data-snapshot-view="${esc(s.id)}"><span class="snapshot-icon">◷</span><span><strong>${esc(s.project)}</strong><small>${new Date(s.created).toLocaleString()} · ${esc(s.state.stage||'Project state')}</small></span><span class="row-arrow">↗</span></button>`).join(''):'<p class="empty-note">No snapshots yet. Open a project and choose “Create snapshot” to preserve its current state.</p>'}`}
renderDirectory();renderProjectList();renderPolicyQueue();renderPlanHistory();renderSnapshots();updateOverviewStats();
const views=['overview','projects','decision','lifecycle','fabrics','agents','councils','governance','knowledge'];
function go(view){if(!views.includes(view))view='overview';$$('.view').forEach(x=>x.classList.remove('active-view'));$('#view-'+view).classList.add('active-view');$$('.nav-item').forEach(x=>x.classList.toggle('active',x.dataset.view===view));const label=$(`[data-view="${view}"]`);$('#crumb').textContent=label?label.textContent.trim().replace(/\s+\d+$/,''):view[0].toUpperCase()+view.slice(1);history.replaceState(null,'','#'+view);window.scrollTo(0,0)}
$$('[data-view]').forEach(a=>a.addEventListener('click',e=>{e.preventDefault();go(a.dataset.view)}));
$$('[data-open]').forEach(b=>b.addEventListener('click',()=>go(b.dataset.open)));
window.addEventListener('hashchange',()=>go(location.hash.slice(1)));
$('#project-search').addEventListener('input',e=>renderDirectory(e.target.value));
$$('.filter').forEach(btn=>btn.addEventListener('click',()=>{$$('.filter').forEach(x=>x.classList.remove('active-filter'));btn.classList.add('active-filter');renderDirectory($('#project-search').value)}));
let toastTimer;function toast(message){const el=$('#toast');el.textContent=message;el.classList.add('show');clearTimeout(toastTimer);toastTimer=setTimeout(()=>el.classList.remove('show'),2500)}
function openModal(content){$('#modal-content').innerHTML=content;$('#modal').classList.add('open');$('#modal').setAttribute('aria-hidden','false');$('#modal-close').focus()}
function closeModal(){$('#modal').classList.remove('open');$('#modal').setAttribute('aria-hidden','true')}
$('#modal-close').addEventListener('click',closeModal);$('#modal').addEventListener('click',e=>{if(e.target===$('#modal'))closeModal()});document.addEventListener('keydown',e=>{if(e.key==='Escape')closeModal()});
function showDetails(category,index){const collection={fabrics,agents,councils,governance,knowledge}[category];if(!collection)return;const item=collection[index];const name=Array.isArray(item)?item[0]:item;const base=Array.isArray(item)?item[1]:'';const data=catalogDetails[category]?.[name];let description=base;let caps=[];let note='';if(category==='fabrics'&&data){description=data[0];caps=data.slice(1,4);note=data[4]}else if(category==='agents'){description=Array.isArray(data)?data[0]:data||base;caps=Array.isArray(data)?data.slice(1):['Receives a scoped task and project context','Returns findings, recommendations, or artifacts','Runs through council and governance routing'];note='Agent implementation and model assignment are not connected in this prototype.'}else if(data){description=Array.isArray(data)?data[0]:data;caps=Array.isArray(data)?data.slice(1):[];note=category==='governance'?'Governance actions in this prototype are stored locally in your browser.':category==='councils'?'Council members are defined in the manifest; live agent execution is not connected yet.':'Project knowledge is currently a local prototype.'}const labels={fabrics:'FABRIC SUBSYSTEM',agents:'SPECIALIST AGENT',councils:'COUNCIL TEMPLATE',governance:'GOVERNANCE CONTROL',knowledge:'KNOWLEDGE AREA'};const related={fabrics:'fabrics',agents:'agents',councils:'councils',governance:'governance',knowledge:'knowledge'}[category];openModal(`<div class="modal-kicker">${labels[category]}</div><h2 id="modal-title">${esc(name)}</h2><p class="modal-description">${esc(description)}</p>${caps.length?`<div class="modal-section"><h4>RESPONSIBILITIES AND CAPABILITIES</h4><div class="capability-list">${caps.map(x=>`<div class="capability">${esc(x)}</div>`).join('')}</div></div>`:''}${note?`<div class="modal-section"><h4>IMPLEMENTATION STATUS</h4><p>${esc(note)}</p></div>`:''}<div class="modal-actions"><button class="secondary-button" data-modal-nav="${related}">Open ${related}</button><button class="primary-button" data-close-modal>Done</button></div>`)}
function showStep(index){const step=decisionSteps[index];openModal(`<div class="modal-kicker">DECISION FORMULA · STAGE ${String(index+1).padStart(2,'0')}</div><h2 id="modal-title">${esc(step[0])}</h2><p class="modal-description">${esc(decisionGuidance[index])}</p><div class="modal-section"><h4>WHAT THIS STAGE NEEDS</h4><div class="capability-list"><div class="capability">${esc(step[1])}</div><div class="capability">Project context and provenance</div>${step[2]?'<div class="capability">Explicit policy and trust result</div><div class="capability">Human approval when policy requires it</div>':''}</div></div><div class="modal-section"><h4>PROTOTYPE BOUNDARY</h4><p>This stage is modeled in the interface. Connecting live providers requires a configured service, credentials, and runtime policy.</p></div><div class="modal-actions"><button class="secondary-button" data-modal-nav="decision">Decision formula</button><button class="primary-button" data-close-modal>Done</button></div>`)}
function stageSelect(value,name='stage'){return `<select name="${name}">${lifecycle.map(x=>`<option ${x[1]===value?'selected':''}>${esc(x[1])}</option>`).join('')}</select>`}
function openProject(name){const p=projects.find(x=>x.name===name);if(!p)return;const ownSnapshots=readStore('projectos.snapshots',[]).filter(s=>s.project===p.name);openModal(`<div class="modal-kicker">PROJECT WORKSPACE</div><h2 id="modal-title">${esc(p.name)}</h2><p class="modal-description">${esc(p.description||`${p.kind} workspace. Project records are stored locally.`)}</p><form class="modal-form" id="edit-project-form"><label>Lifecycle stage ${stageSelect(p.stage)}</label><label>Project type<input name="kind" value="${esc(p.kind)}" maxlength="50"></label><div class="modal-status">Current state: ${esc(p.stage)} · ${esc(p.health)}. Moving to Archive or Template records that stage; it does not delete this project.</div>${ownSnapshots.length?`<div class="modal-section"><h4>RECENT SNAPSHOTS</h4>${ownSnapshots.slice(0,3).map(s=>`<p>${new Date(s.created).toLocaleString()} · ${esc(s.state.stage||'Project state')}</p>`).join('')}</div>`:''}<div class="modal-actions"><button type="button" class="secondary-button" data-snapshot="${esc(p.name)}">Create snapshot</button><button type="button" class="secondary-button" data-close-modal>Cancel</button><button type="submit" class="primary-button">Save project</button></div></form>`);$('#edit-project-form').addEventListener('submit',e=>{e.preventDefault();const fd=new FormData(e.currentTarget);p.stage=fd.get('stage');p.kind=fd.get('kind').trim()||'Project';p.updated='Just now';persistProjects();closeModal();toast(`${p.name} updated.`)})}
function createSnapshot(name){const project=projects.find(p=>p.name===name);if(!project)return;const snapshots=readStore('projectos.snapshots',[]);const state=JSON.parse(JSON.stringify(project));snapshots.unshift({id:globalThis.crypto?.randomUUID?.()||`${Date.now()}-${Math.random().toString(36).slice(2)}`,project:project.name,created:new Date().toISOString(),state});writeStore('projectos.snapshots',snapshots);renderSnapshots();updateOverviewStats();closeModal();toast(`Snapshot saved for ${project.name}.`)}
function openSnapshot(id){const snapshot=readStore('projectos.snapshots',[]).find(s=>s.id===id);if(!snapshot)return;openModal(`<div class="modal-kicker">PROJECT SNAPSHOT · ${new Date(snapshot.created).toLocaleString()}</div><h2 id="modal-title">${esc(snapshot.project)}</h2><p class="modal-description">Saved state: ${esc(snapshot.state.stage)} · ${esc(snapshot.state.kind||'Project')}</p>${snapshot.state.description?`<div class="modal-section"><h4>PROJECT DESCRIPTION</h4><p>${esc(snapshot.state.description)}</p></div>`:''}<div class="modal-status">This snapshot preserves the project record at the time it was created. It does not yet capture files or external service state.</div><div class="modal-actions"><button class="primary-button" data-close-modal>Done</button></div>`)}
function openNewProject(){openModal(`<div class="modal-kicker">PROJECTS · CREATE</div><h2 id="modal-title">Start a project</h2><p class="modal-description">Create a local project workspace. You can update its stage and type as it evolves.</p><form class="modal-form" id="new-project-form"><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>Initial description<textarea name="description" maxlength="300" placeholder="What outcome should this project support?"></textarea></label><div class="modal-actions"><button type="button" class="secondary-button" data-close-modal>Cancel</button><button type="submit" class="primary-button">Create project</button></div></form>`);$('#new-project-form').addEventListener('submit',e=>{e.preventDefault();const fd=new FormData(e.currentTarget);const name=String(fd.get('name')).trim();if(projects.some(p=>p.name.toLowerCase()===name.toLowerCase())){toast('A project with that name already exists.');return}const tones=['violet','blue','orange','green'];projects.unshift({name,initial:name[0].toUpperCase(),tone:tones[projects.length%tones.length],stage:'Research',kind:String(fd.get('kind')).trim()||'General',description:String(fd.get('description')).trim(),updated:'Just now',health:'Healthy'});persistProjects();closeModal();go('projects');toast(`Project “${name}” created.`)})}
function openStageChange(initial='Active'){if(!projects.length){toast('Create a project before updating its lifecycle stage.');return}openModal(`<div class="modal-kicker">LIFECYCLE · UPDATE</div><h2 id="modal-title">Move a project to a new stage</h2><p class="modal-description">Lifecycle changes are saved to the local project record.</p><form class="modal-form" id="stage-form"><label>Project<select name="project">${projects.map(p=>`<option value="${esc(p.name)}">${esc(p.name)} · ${esc(p.stage)}</option>`).join('')}</select></label><label>New stage ${stageSelect(initial)}</label><div class="modal-actions"><button type="button" class="secondary-button" data-close-modal>Cancel</button><button type="submit" class="primary-button">Update stage</button></div></form>`);$('#stage-form').addEventListener('submit',e=>{e.preventDefault();const fd=new FormData(e.currentTarget);const p=projects.find(x=>x.name===fd.get('project'));if(p){p.stage=fd.get('stage');p.updated='Just now';persistProjects();closeModal();toast(`${p.name} moved to ${p.stage}.`)}})}
function openStageDetail(index){const [number,name,short]=lifecycle[index];openModal(`<div class="modal-kicker">PROJECT LIFECYCLE · STAGE ${number}</div><h2 id="modal-title">${esc(name)}</h2><p class="modal-description">${esc(short)}. This stage represents a distinct project state in the ProjectOS lifecycle.</p><div class="modal-section"><h4>HOW IT FITS</h4><p>${index<3?'A project establishes context and becomes active work before it moves into production.':index<8?'The evolution stages compare the current state with a target, expose gaps, and turn them into improvement suggestions.': 'Retirement preserves project state in snapshots, then archives the work so its proven patterns can become a template.'}</p></div><div class="modal-actions"><button class="secondary-button" data-close-modal>Close</button><button class="primary-button" data-set-stage="${esc(name)}">Set project stage</button></div>`)}
function localPlan(question,project){const q=question.toLowerCase();const council=/policy|permission|trust|privacy|risk|approval|audit/.test(q)?'Governance Council':/deploy|database|docker|runtime|infrastructure|install|server/.test(q)?'Infrastructure Council':/design|architecture|system|structure|interface/.test(q)?'Architecture Council':/build|implement|code|create|app|feature|fix/.test(q)?'Implementation Council':/improv|evol|compare|roadmap|gap|frontier/.test(q)?'Evolution Council':'Research Council';return{question,project:project||'Workspace level',intent:'local-preview',council,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'],model:'Not configured',datasets:project?`${project} project context (local prototype)`:'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()}}
function savePlan(plan){const plans=readStore('projectos.plans',[]).filter(x=>x.id!==plan.id);plans.unshift(plan);writeStore('projectos.plans',plans.slice(0,100));renderPlanHistory();showPlan(plan)}
function openPlanner(){openModal(`<div class="modal-kicker">OPERATIONS AGENT · LOCAL PLANNING PREVIEW</div><h2 id="modal-title">Plan a question</h2><p class="modal-description">Describe the outcome you want. ProjectOS drafts an intent, council, and specialist plan for review; it will not execute external actions.</p><form class="modal-form" id="plan-form"><label>Your question<textarea name="question" required maxlength="700" placeholder="What are you trying to learn or build?"></textarea></label><label>Project context<select name="project"><option value="">Workspace level</option>${projects.map(p=>`<option value="${esc(p.name)}">${esc(p.name)}</option>`).join('')}</select></label><div class="modal-actions"><button type="button" class="secondary-button" data-close-modal>Cancel</button><button type="submit" class="primary-button">Generate plan</button></div></form>`);$('#plan-form').addEventListener('submit',async e=>{e.preventDefault();const form=e.currentTarget;const fd=new FormData(form);const question=String(fd.get('question')).trim();const selected=projects.find(p=>p.name===fd.get('project'));const project=selected?.name||'';const submit=form.querySelector('[type="submit"]');submit.disabled=true;submit.textContent='Planning…';let plan;if(location.protocol==='http:'&&['localhost','127.0.0.1'].includes(location.hostname)){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');plan=await response.json()}catch{toast('Local planning service unavailable; using the browser planner.')}}plan??=localPlan(question,project);savePlan(plan)})}
function showPlan(plan){const missing=plan.governanceGate?.missingIntegrations||[];const names={modelProvider:'Model provider',datasetProvider:'Dataset provider',toolAdapter:'Tool adapter',identityProvider:'Identity provider'};openModal(`<div class="modal-kicker">PLANNING PREVIEW · NOT EXECUTED</div><h2 id="modal-title">${esc(plan.question)}</h2><p class="modal-description">${esc(plan.project)} · ${plan.intent?`${esc(plan.intent)} intent · `:''}Suggested ${esc(plan.council)}</p><div class="modal-section"><h4>ASSIGNED SPECIALISTS</h4><div class="capability-list">${plan.agents.map(a=>`<div class="capability">${esc(a)}</div>`).join('')}</div></div><div class="modal-section"><h4>ROUTING</h4><p><strong>Model:</strong> ${esc(plan.model)}</p><p><strong>Dataset:</strong> ${esc(plan.datasets)}</p><p><strong>Tools:</strong> ${esc(plan.tools)}</p></div><div class="modal-section"><h4>VALIDATION GATES</h4><p><strong>Logic:</strong> ${esc(plan.logic)}</p><p><strong>Governance:</strong> ${esc(plan.governance)}</p>${missing.length?`<div class="capability-list">${missing.map(x=>`<div class="capability">Missing: ${esc(names[x]||x)}</div>`).join('')}</div><p>Human approval: ${plan.governanceGate.approvalRequired?'required':'not required'}</p>`:''}</div><div class="modal-status">This is a local planning draft. It is saved for review and cannot execute until its integrations and governance requirements are satisfied.</div><div class="modal-actions"><button class="secondary-button" data-modal-nav="decision">View decision flow</button><button class="primary-button" data-close-modal>Done</button></div>`)}
$('#new-project').addEventListener('click',openNewProject);$('#new-project-2').addEventListener('click',openNewProject);$('#start-planning').addEventListener('click',openPlanner);$('#advance-project').addEventListener('click',()=>openStageChange());
$('#review-policies').addEventListener('click',()=>$('#policy-queue').scrollIntoView({behavior:'smooth',block:'center'}));
document.addEventListener('click',e=>{
const card=e.target.closest('[data-category]');if(card){showDetails(card.dataset.category,Number(card.dataset.index));return}
const step=e.target.closest('[data-step]');if(step){showStep(Number(step.dataset.step));return}
const stage=e.target.closest('[data-stage]');if(stage){openStageDetail(Number(stage.dataset.stage));return}
const snapshotButton=e.target.closest('[data-snapshot]');if(snapshotButton){createSnapshot(snapshotButton.dataset.snapshot);return}
const snapshotRow=e.target.closest('[data-snapshot-view]');if(snapshotRow){openSnapshot(snapshotRow.dataset.snapshotView);return}
const project=e.target.closest('[data-project]');if(project){openProject(project.dataset.project);return}
const close=e.target.closest('[data-close-modal]');if(close){closeModal();return}
const nav=e.target.closest('[data-modal-nav]');if(nav){const target=nav.dataset.modalNav;closeModal();go(target);return}
const setStage=e.target.closest('[data-set-stage]');if(setStage){openStageChange(setStage.dataset.setStage);return}
const policy=e.target.closest('[data-policy]');if(policy){const items=readStore('projectos.policies',seedPolicies);const item=items.find(x=>x.id===policy.dataset.policy);if(item){item.status=policy.dataset.decision;item.reviewed=new Date().toISOString();writeStore('projectos.policies',items);renderPolicyQueue();updateOverviewStats();toast(`${item.title}: ${item.status.toLowerCase()}.`)}return}
const historyEntry=e.target.closest('[data-plan]');if(historyEntry){const plan=readStore('projectos.plans',[])[Number(historyEntry.dataset.plan)];if(plan)showPlan(plan)}
});
if(location.hash)go(location.hash.slice(1));
async function connectLocalApi(){
if(location.protocol!=='http:'||!['localhost','127.0.0.1'].includes(location.hostname))return;
try{
const response=await fetch('/api/state');if(!response.ok)throw new Error('Local state API unavailable');
const state=await response.json();
for(const [name,key,fallback] of [['projects','projectos.projects',projects],['policies','projectos.policies',seedPolicies],['plans','projectos.plans',[]],['snapshots','projectos.snapshots',[]]]){
if(Array.isArray(state[name])){try{localStorage.setItem(key,JSON.stringify(state[name]))}catch{};if(name==='projects')projects=state[name]}
else writeStore(key,readStore(key,fallback));
}
renderDirectory($('#project-search').value);renderProjectList();renderPolicyQueue();renderPlanHistory();renderSnapshots();updateOverviewStats();
}catch{toast('Local database is unavailable; using browser storage for this session.')}
}
connectLocalApi();
loadGeneratedConfig().catch(()=>toast('Generated ProjectOS configuration could not be loaded.'));
|