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 => `${esc(p.initial||p.name?.[0]||'?')}`; const projectStatus = p => ` ${p.stage}`; 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)=>`
${String(i+1).padStart(2,'0')}${s[0]}
`).join(''); $('#formula-list').innerHTML = decisionSteps.map((s,i)=>``).join(''); $('#lifecycle-board').innerHTML = lifecycle.map((s,i)=>``).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 ``}).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?'→':''}`}).join('')} renderKnowledgePipeline(); function renderProjectList(){ $('#project-list').innerHTML=projects.slice(0,4).map(p=>``).join('')||'

No projects yet. Create one to get started.

' } 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=>``).join('')||'
No projects match your search.
'} function persistProjects(){writeStore('projectos.projects',projects);renderDirectory($('#project-search')?.value||'');renderProjectList();updateOverviewStats()} function renderPlanHistory(){const plans=readStore('projectos.plans',[]);$('#plan-history').innerHTML=plans.length?`

Recent planning runs

${plans.slice(0,5).map((p,i)=>`
⌘
${esc(p.question)}${esc(p.council)} · ${new Date(p.created).toLocaleString()}
`).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=`

Review queue

Decisions are saved in this browser and local database when running the API.

${pending} pending
${items.length?items.map(item=>`
${esc(item.title)}

${esc(item.description)}

${esc(item.status)}${item.status==='Pending'?``:''}
`).join(''):'

No policy proposals. The review queue is clear.

'}`} 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)=>`
${String(i+1).padStart(2,'0')}${esc(s[0])}
`).join(''); $('#formula-list').innerHTML=decisionSteps.map((s,i)=>``).join(''); $('#lifecycle-board').innerHTML=lifecycle.map((s,i)=>``).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=`

Project snapshots

Saved state records stored locally.

${snapshots.length} total
${snapshots.length?snapshots.slice(0,8).map(s=>``).join(''):'

No snapshots yet. Open a project and choose “Create snapshot” to preserve its current state.

'}`} 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(`${caps.length?``:''}${note?``:''}`)} function showStep(index){const step=decisionSteps[index];openModal(``)} function stageSelect(value,name='stage'){return ``} 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(``);$('#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(`${snapshot.state.description?``:''}`)} function openNewProject(){openModal(``);$('#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(``);$('#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(``)} 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(``);$('#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(``)} $('#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.'));