workspai 0.70.0 → 0.72.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -80
- package/contracts/artifact-remediation-plan.v1.json +49 -0
- package/contracts/workspace-intelligence/goal-lifecycle-result.v1.json +19 -0
- package/contracts/workspace-repair-capabilities.v1.json +7 -1
- package/dist/analyze-5ENZTHOT.js +1 -0
- package/dist/{artifact-remediation-plan-URQL5MBN.js → artifact-remediation-plan-WDK5ISRU.js} +1 -1
- package/dist/autopilot-release-PNSWAVZG.js +1 -0
- package/dist/{chunk-EP6Q2QBU.js → chunk-2RF75G5T.js} +1 -1
- package/dist/{chunk-4R7STECB.js → chunk-5OLNT6YD.js} +63 -63
- package/dist/{chunk-GED7JURY.js → chunk-5PFFR5S7.js} +1 -1
- package/dist/{chunk-QZODGRAI.js → chunk-5TKRCE6F.js} +1 -1
- package/dist/{chunk-IGJA6GBQ.js → chunk-62YBFWHY.js} +1 -1
- package/dist/chunk-6WOFOOM7.js +7 -0
- package/dist/{chunk-ZLCLGIM6.js → chunk-7LKCWDX6.js} +1 -1
- package/dist/chunk-7Q7X4X5I.js +1 -0
- package/dist/chunk-BVWDG66W.js +1 -0
- package/dist/{chunk-DNZHKBQ3.js → chunk-COBU44T5.js} +1 -1
- package/dist/chunk-CQBM6BBP.js +2 -0
- package/dist/chunk-CY4QZ3PE.js +3 -0
- package/dist/{chunk-LE2I2E6R.js → chunk-D5RUGSBC.js} +2 -2
- package/dist/chunk-EDPUQXP6.js +5 -0
- package/dist/{chunk-IBJEQHJR.js → chunk-HV6EQMUJ.js} +24 -7
- package/dist/{chunk-V52R2W2Q.js → chunk-IX5Z6EK6.js} +1 -1
- package/dist/{chunk-N6FJZ62B.js → chunk-JQINCVK5.js} +1 -1
- package/dist/{chunk-GL3KLNIG.js → chunk-KVPTZMEV.js} +1 -1
- package/dist/{chunk-UT57IFS4.js → chunk-LDNX2R6V.js} +6 -6
- package/dist/{chunk-WUXJCSYO.js → chunk-LLEKVSMX.js} +1 -1
- package/dist/{chunk-ZPOZ6MDX.js → chunk-N2PAAQKI.js} +1 -1
- package/dist/{chunk-S2TOSHQW.js → chunk-ONV6WW7A.js} +1 -1
- package/dist/{chunk-TEMFNVO2.js → chunk-QVUVJU56.js} +1 -1
- package/dist/{chunk-AGZWDYMF.js → chunk-QYXX6G5O.js} +8 -8
- package/dist/{chunk-S42KDOGG.js → chunk-S66NO5BX.js} +1 -1
- package/dist/{chunk-KFTJVVJR.js → chunk-SATPH22S.js} +1 -1
- package/dist/{chunk-IFHM2SI6.js → chunk-SG3QRCMM.js} +1 -1
- package/dist/{chunk-Z7JIUA6I.js → chunk-SS7X2YF5.js} +1 -1
- package/dist/{chunk-IET57ZKN.js → chunk-T6KHOIEY.js} +1 -1
- package/dist/{chunk-TLMP2MGH.js → chunk-T6LCDLJ7.js} +1 -1
- package/dist/{chunk-QNHKUSBH.js → chunk-TDQ2PRHV.js} +1 -1
- package/dist/{chunk-3S2U7WRM.js → chunk-TQQEZQLC.js} +1 -1
- package/dist/{chunk-LU6CYDLN.js → chunk-UHAPXPGW.js} +1 -1
- package/dist/chunk-V4LCPLV6.js +1 -0
- package/dist/{chunk-GYN6RPNU.js → chunk-WMC2H7MJ.js} +1 -1
- package/dist/{chunk-PTSEDZIV.js → chunk-WPZUKU2B.js} +1 -1
- package/dist/chunk-X5ZNFXFI.js +1 -0
- package/dist/{create-BBALBC3U.js → create-7CWWGDXQ.js} +1 -1
- package/dist/{doctor-WWVY7NB6.js → doctor-WYBSI3GC.js} +1 -1
- package/dist/{dotnet-webapi-clean-XL4IBUQV.js → dotnet-webapi-clean-VJX6SGGP.js} +39 -33
- package/dist/{goal-lifecycle-CEUTKUNV.js → goal-lifecycle-PSPYQ4TR.js} +1 -1
- package/dist/{goal-pack-JQL3YOKT.js → goal-pack-G7SAYDIC.js} +1 -1
- package/dist/{gofiber-standard-OHHMCNMJ.js → gofiber-standard-I6ASLOEE.js} +77 -66
- package/dist/{gogin-standard-BAZXPOKL.js → gogin-standard-U2LSRLIP.js} +78 -67
- package/dist/index.js +121 -121
- package/dist/{pipeline-V46WWMP4.js → pipeline-NDV7DBB7.js} +1 -1
- package/dist/{project-agent-entry-MRAYG7QD.js → project-agent-entry-HEBGPLMX.js} +1 -1
- package/dist/{project-intelligence-lens-4BKPN4PE.js → project-intelligence-lens-QTQEZXUY.js} +1 -1
- package/dist/{project-test-coverage-4RRCHY5W.js → project-test-coverage-4BGDDBBL.js} +1 -1
- package/dist/{proof-carrying-change-B7ONTBYO.js → proof-carrying-change-SHO2E3DX.js} +1 -1
- package/dist/{rust-axum-CCJ6UCBW.js → rust-axum-JMV7UPO7.js} +25 -20
- package/dist/{springboot-standard-M5JQEJML.js → springboot-standard-OC2RS3KC.js} +41 -39
- package/dist/verified-goal-BSREU6R7.js +1 -0
- package/dist/{workspace-FJ6JRYWA.js → workspace-E3MM3AIE.js} +1 -1
- package/dist/{workspace-agent-sync-V33UGII3.js → workspace-agent-sync-NBIOSXCG.js} +1 -1
- package/dist/{workspace-context-O6UBCBEA.js → workspace-context-ZDXF6S7S.js} +1 -1
- package/dist/{workspace-contract-S2JYDA4K.js → workspace-contract-E7GVWM7W.js} +1 -1
- package/dist/{workspace-explain-RP6VJ6QM.js → workspace-explain-YB66UFAS.js} +1 -1
- package/dist/{workspace-foundation-7QXEJJKZ.js → workspace-foundation-LRLYPR36.js} +1 -1
- package/dist/{workspace-graph-stream-YY65R5EC.js → workspace-graph-stream-SJUCBPS4.js} +1 -1
- package/dist/workspace-graph-token-efficiency-BTIS6JXL.js +1 -0
- package/dist/{workspace-intelligence-LMR42ICR.js → workspace-intelligence-3IAAM3H3.js} +1 -1
- package/dist/{workspace-intelligence-benchmark-S5OXVNLC.js → workspace-intelligence-benchmark-UCGDKMDF.js} +1 -1
- package/dist/{workspace-intelligence-runner-FXFSTCHC.js → workspace-intelligence-runner-FPPKTSNK.js} +1 -1
- package/dist/{workspace-knowledge-graph-3564KQXT.js → workspace-knowledge-graph-WNQMNAVL.js} +1 -1
- package/dist/{workspace-knowledge-graph-query-WHCGPBGS.js → workspace-knowledge-graph-query-3GPXGWYN.js} +1 -1
- package/dist/workspace-knowledge-graph-snapshot-MTFTCVFF.js +1 -0
- package/dist/{workspace-mcp-serve-ZK46EZUD.js → workspace-mcp-serve-KSZ2O66S.js} +1 -1
- package/dist/{workspace-model-6UMQAGUK.js → workspace-model-5FA2636K.js} +1 -1
- package/dist/{workspace-onboarding-C57OQ7XZ.js → workspace-onboarding-RJMTHN7Z.js} +1 -1
- package/dist/{workspace-registry-summary-GLQO4ZUF.js → workspace-registry-summary-WKENOFEA.js} +1 -1
- package/dist/workspace-repair-engine-4JTNNDZL.js +3 -0
- package/dist/workspace-run-HFOY2UYT.js +1 -0
- package/dist/{workspace-verify-LQHXBH2D.js → workspace-verify-37QL2JYE.js} +1 -1
- package/dist/{workspace-watch-Z32443UP.js → workspace-watch-P5X6TAFK.js} +1 -1
- package/docs/README.md +5 -2
- package/docs/README_CONTENT_CONTRACT.md +14 -9
- package/docs/ci-workflows.md +1 -1
- package/docs/commands-reference.md +53 -34
- package/docs/contracts/ARTIFACT_CATALOG.md +4 -1
- package/docs/doctor-command.md +13 -0
- package/docs/native-kit-baselines.md +82 -0
- package/docs/workspace-knowledge-graph.md +17 -2
- package/docs/workspace-repair-engine.md +9 -1
- package/docs/workspace-run.md +29 -0
- package/package.json +1 -1
- package/dist/analyze-OGWDSPXQ.js +0 -1
- package/dist/autopilot-release-QQDFEPT7.js +0 -1
- package/dist/chunk-DWL3PPLA.js +0 -1
- package/dist/chunk-EZPLMAW2.js +0 -1
- package/dist/chunk-IHKG5C6G.js +0 -1
- package/dist/chunk-IRLKWRLP.js +0 -3
- package/dist/chunk-TKXRP2B4.js +0 -1
- package/dist/chunk-U5ENEDJA.js +0 -7
- package/dist/chunk-WCJU3CFG.js +0 -1
- package/dist/chunk-XSSNM4F5.js +0 -5
- package/dist/verified-goal-YNSBL7L3.js +0 -1
- package/dist/workspace-graph-token-efficiency-WNAFAN2F.js +0 -1
- package/dist/workspace-knowledge-graph-snapshot-P27RPMV5.js +0 -1
- package/dist/workspace-repair-engine-5ZSSF3T5.js +0 -3
- package/dist/workspace-run-UGWGT3K2.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {m,a as a$1,l as l$1}from'./chunk-
|
|
1
|
+
import {m,a as a$1,l as l$1}from'./chunk-5PFFR5S7.js';import {b as b$5,g as g$2}from'./chunk-5TKRCE6F.js';import {b as b$4,a}from'./chunk-D5LLTUTY.js';import {b as b$2,f as f$2,s as s$1,t as t$1,u,P as P$1,v,q as q$2,r,R,n,o,p as p$2,h as h$2,i,m as m$1,j,k,l,O,w,x,y,z as z$1,A,B as B$1,C,E,G,I,D as D$1,F,H,J as J$1,K,L,M,N,S,T,U,V,Y as Y$1,X as X$1,W,a as a$3,Q}from'./chunk-QYEQVNBF.js';import {b as b$1,c,d}from'./chunk-JQINCVK5.js';import {b as b$3}from'./chunk-COICGD62.js';import {d as d$2}from'./chunk-S66NO5BX.js';import {b as b$7}from'./chunk-QYXX6G5O.js';import {q as q$1,l as l$2,d as d$1}from'./chunk-BVWDG66W.js';import {p as p$1}from'./chunk-WPZUKU2B.js';import {g}from'./chunk-FE5R6EUV.js';import {a as a$2,b as b$6}from'./chunk-K33JJVQZ.js';import {q,p,t,s as s$2}from'./chunk-ODK4LCEL.js';import {f as f$1,g as g$1,h}from'./chunk-VQZ5PI5J.js';import s from'path';import h$1 from'fs-extra';var pe=["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"];var Jt="workspace-operational-skill.v1";function Yt(e){if(typeof e!="string")return null;let t=e.trim();return !t||t.includes("/")||t.includes("..")?null:t}function Ot(e){let t=Yt(e.skillId);if(!t)throw new Error(`Invalid skill id: ${e.skillId}`);return {schemaVersion:Jt,skillId:t,canonicalPath:W(t),title:e.title,triggers:[...e.triggers].sort((r,n)=>r.localeCompare(n)),requiredReports:[...e.requiredReports].sort((r,n)=>r.localeCompare(n)),scopedProjects:[...e.scopedProjects??[]].sort((r,n)=>r.localeCompare(n)),verificationCommands:[...e.verificationCommands],answerContractSections:[...pe],...e.promptStem?{promptStem:e.promptStem}:{},markdown:e.markdown}}var Xt=q.skillsIndex;function Tt(e){let t=[...e.skills].sort((i,c)=>i.skillId.localeCompare(c.skillId)),r=e.inputsHash??d$1({skillIds:t.map(i=>i.skillId),paths:t.map(i=>i.canonicalPath),decisions:e.decisions??[]}),n=e.decisions?[...e.decisions].sort((i,c)=>i.skillId.localeCompare(c.skillId)):void 0;return {schemaVersion:Xt,generatedAt:e.generatedAt,inputsHash:r,skills:t.map(i=>({skillId:i.skillId,path:i.canonicalPath,schemaVersion:i.schemaVersion,title:i.title})),...n?{selection:{generatedCount:n.filter(i=>i.status==="generated").length,suppressedCount:n.filter(i=>i.status==="suppressed").length,decisions:n}}:{}}}var _t=[p.agentIndex,b$1,d$2],B="<!-- WORKSPAI:GENERATED-OPERATIONAL-SKILL -->",Qt=[{skillId:"workspai-diagnose-api-failure",title:"Diagnose API failure",triggers:["api failure","500 error","integration test failed","service unreachable"],objective:"Investigate a failing API or service using Workspai evidence before editing application code.",steps:[`Read \`${p.agentIndex}\` and identify fail/warn reports for the scoped project.`,`Read \`${p.doctor}\`, \`doctor-project-last-run.json\`, and project-scoped run evidence if present.`,"If a fix was requested, read `artifact-remediation-plan-last-run.json` for cross-artifact next steps, then `doctor-remediation-plan-last-run.json` for Doctor-specific file edits.","Map the failure to workspace vs project scope; cite exit codes and blocker messages.","Propose the smallest safe fix (config, env, dependency) with explicit verification commands."],applicability:"api"},{skillId:"workspai-release-readiness",title:"Release readiness",triggers:["release","ship","production","readiness gate"],objective:"Assess whether this workspace is release-ready using governed Workspai gates.",steps:[`Read \`${p.readiness}\` and \`pipeline-last-run.json\`.`,`Read \`${p.verify}\` for verdict and blocking reasons.`,`Read \`${t.artifactRemediationPlan}\` when a Studio or agent repair path is needed.`,"List blocking gates first; never claim ready without cited report fields.","Provide one safe next command and a verification checklist."],applicability:"workspace"},{skillId:"workspai-safe-schema-migration",title:"Safe schema migration",triggers:["migration","schema change","database migration","db migrate"],objective:"Plan and verify a schema migration with blast-radius awareness.",steps:["Identify affected projects from workspace model and dependency graph.","Run or review impact/verify evidence for transitive dependents.","Run a registered project-scoped test/build command when available; otherwise resolve the repository-authored validation command from cited manifests before promoting the migration.","Document rollback and verification signals."],applicability:"schema"},{skillId:"workspai-dependency-upgrade",title:"Dependency upgrade",triggers:["upgrade dependency","bump package","security advisory","outdated deps"],objective:"Upgrade dependencies with graph-aware verification.",steps:["Scope the upgrade to the owning project from workspace model.","Check transitive dependents via workspace graph / impact reports.","Use registered test/build commands for affected projects; when none are registered, resolve repository-authored commands from cited manifests instead of inventing one.","Re-run `workspace verify` after evidence refresh."],applicability:"dependency"},{skillId:"workspai-rename-contract",title:"Rename contract safely",triggers:["rename contract","rename event","breaking api","contract change"],objective:"Rename or change a shared contract with consumer awareness.",steps:[`Read \`${t.workspaceContract}\` for publishes/consumes/owns edges.`,"List all consumer projects before proposing renames.","Update contract file and regenerate workspace model.","Verify contract gate and integration tests for consumers."],applicability:"contract"}];function z(e){return `npx workspai ${e}`.trim()}function Zt(e){let t=["---",`name: ${e.template.skillId}`,`description: ${e.template.objective}`,"---","",B,"",`# ${e.template.title}`,"",`> Workspace: **${e.workspaceName}** \xB7 Skill: \`${e.template.skillId}\``,"","## Objective","",e.template.objective,"","## Triggers","",...e.template.triggers.map(r=>`- ${r}`),"","## Required evidence (read first)","",..._t.map(r=>`- \`${r}\``),"","## Why this skill exists here","",`Applicability: **${e.decision.confidence} confidence**.`,"",...e.decision.reasons.map(r=>`- ${r}`),...e.decision.signals.length>0?["","Evidence signals:","",...e.decision.signals.map(r=>`- \`${r}\``)]:[],"","## Project-aware execution boundary","",...e.projectEvidence,"",...e.retrievalCommands.length>0?["## Scoped retrieval commands","",...e.retrievalCommands.map(r=>`- \`${r}\``),""]:[],"## Procedure","",...e.template.steps.map((r,n)=>`${n+1}. ${r}`),""];if(e.scopedProjects.length>0&&t.push("## Scoped projects","",...e.scopedProjects.map(r=>`- ${r}`),""),e.contractSummary&&t.push("## Contract context","",e.contractSummary,""),e.verificationCommands.length>0){t.push("## Verification commands (this workspace)","");for(let r of e.verificationCommands)t.push(`- \`${r}\``);t.push("");}return t.push("## Answer contract","","Return: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh stale evidence","","```bash",z("workspace agent-sync --write --refresh-context"),"```",""),t.join(`
|
|
2
2
|
`)}function er(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function tr(e){let t=new Map;for(let c of e.projects){let m=new Set([c.runtime,...c.runtimeCandidates??[]].map(er).filter(a=>a&&a!=="unknown"));for(let a of m){let k=t.get(a)??[];k.includes(c.name)||k.push(c.name),t.set(a,k);}}let r=[];for(let[c,m]of [...t.entries()].sort(([a],[k])=>a.localeCompare(k)))r.push({skillId:`workspai-${c}-runtime-validation`,title:`${c.toUpperCase()} runtime validation`,triggers:[`${c} build`,`${c} test`,`${c} runtime failure`],objective:`Validate ${c} changes against the detected runtime boundary, registered project commands, and canonical Workspai evidence.`,steps:["Read the scoped project lens and current fail/warn evidence before changing source.",`Use a registered ${c} command only when the project model identifies ${c} as the primary runtime; for a composite secondary boundary, inspect its manifest and Graph proofs instead of assuming the primary adapter covers it.`,"Run only the affected project validation first, then verify the workspace when the change crosses a contract boundary."],scopedProjects:[...m].sort(),applicability:"derived"});t.size>1&&r.push({skillId:"workspai-polyglot-change-validation",title:"Polyglot change validation",triggers:["cross-language change","polyglot change","binding change","multi-runtime validation"],objective:"Plan and verify a cross-runtime change without assuming that one runtime command proves the whole system.",steps:["Use the project topology and bounded Graph query to identify runtime and contract boundaries.","Validate each affected runtime with its registered project command.","Run workspace impact and canonical verification before declaring the change complete."],scopedProjects:Wt([...t.values()].flat()),applicability:"derived"});let n=e.projects.filter(c=>c.commands.supported.includes("test")).map(c=>c.name).sort();n.length>0&&r.push({skillId:"workspai-test-evidence-recovery",title:"Test evidence recovery",triggers:["test failure","coverage","regression","test evidence"],objective:"Repair a test or coverage blocker by proving changed behavior, not merely improving a metric.",steps:["Read the exact Analyze, Doctor, or Goal evidence that owns the test finding.","Inspect the behavior and relevant test boundary before proposing a source change.","Run the scoped test command, then the exact producer and canonical verification."],scopedProjects:n,applicability:"derived"});let i=e.projects.filter(c=>c.importantFiles.some(m=>/(?:^|\/)(?:Dockerfile|docker-compose|compose\.|Chart\.yaml|\.github\/workflows)/i.test(m))).map(c=>c.name).sort();return i.length>0&&r.push({skillId:"workspai-delivery-evidence",title:"Delivery evidence and CI recovery",triggers:["ci failure","workflow failure","container build","deployment evidence"],objective:"Diagnose delivery evidence with the owning project and CI/container artifacts before changing application source.",steps:["Identify whether the failing evidence is project-owned or workspace-owned.","Inspect the referenced workflow or delivery artifact and its bounded proof paths.","Validate the affected project first, then refresh the exact evidence producer and verify the workspace."],scopedProjects:i,applicability:"derived"}),r}function rr(e,t){if(!e?.safeCommands?.length)return [z("workspace verify --json"),z("doctor workspace --json")];let r=new Set(t);return e.safeCommands.filter(n=>n.scope==="workspace"||n.project&&r.has(n.project)).slice(0,8).map(n=>n.display)}function nr(e,t){if(!e?.projects?.length)return;let r=new Set(t),n=e.projects.filter(i=>r.has(i.slug)).filter(i=>(i.contracts?.owns?.length??0)>0||(i.contracts?.publishes?.length??0)>0||(i.contracts?.consumes?.length??0)>0||(i.contracts?.apis?.length??0)>0).slice(0,12).map(i=>{let c=i.contracts?.owns?.join(", ")||"none",m=i.contracts?.publishes?.join(", ")||"none",a=i.contracts?.consumes?.join(", ")||"none";return `- **${i.slug}**: owns \`${c}\`; publishes \`${m}\`; consumes \`${a}\``});return n.length>0?n.join(`
|
|
3
3
|
`):void 0}var ar=/(?:^|\/)(?:package(?:-lock)?\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?|pyproject\.toml|poetry\.lock|requirements[^/]*\.txt|Pipfile(?:\.lock)?|uv\.lock|Cargo\.toml|Cargo\.lock|go\.mod|go\.sum|pom\.xml|build\.gradle(?:\.kts)?|settings\.gradle(?:\.kts)?|Gemfile(?:\.lock)?|composer\.(?:json|lock)|mix\.exs|deps\.edn|project\.clj|[^/]+\.(?:csproj|fsproj|vbproj)|Directory\.Packages\.props)$/i,or=/(?:^|\/)(?:openapi|swagger|asyncapi)\.(?:json|ya?ml)$|(?:^|\/)(?:routes?|controllers?|endpoints?|proto)(?:\/|\.)/i,ir=/(?:^|\/)(?:migrations?|database|db|prisma)(?:\/|\.)|(?:^|\/)schema\.(?:sql|prisma)$/i;function sr(e){let t=e.attributes.artifact;return typeof t=="string"&&t.trim()?t.trim():null}function cr(e){let t=e.attributes.ports;return Array.isArray(t)&&t.length>0}function lr(e,t){return e?.entities.filter(r=>r.projectId===t)??[]}function ue(e,t=12){return [...new Set([...e].map(r=>r.trim()).filter(Boolean))].sort((r,n)=>r.localeCompare(n)).slice(0,t)}function Wt(e){return [...new Set([...e].map(t=>t.trim()).filter(Boolean))].sort((t,r)=>t.localeCompare(r))}function dr(e){if(e.template.scopedProjects)return {projects:[...e.template.scopedProjects].sort(),reasons:["The canonical workspace model directly derived this capability."],signals:ue(e.template.scopedProjects.map(i=>`model:project:${i}:${e.template.skillId}`)),confidence:"high",applicable:true};if(e.template.applicability==="workspace")return {projects:e.model.projects.map(i=>i.name).sort(),reasons:["Workspace-level release and verification gates are always available."],signals:["model:workspace",`model:project-count:${e.model.projects.length}`],confidence:"high",applicable:true};let t=[],r=[],n=new Set;for(let i of e.model.projects){let c=lr(e.graph,i.name),m=Wt([...i.importantFiles,...c.map(sr).filter(l=>!!l)]),a=e.contract?.projects.find(l=>l.slug===i.name),k=false;switch(e.template.applicability){case "dependency":{let l=m.filter(d=>ar.test(d)),p=c.filter(d=>d.kind==="package");k=l.length>0||p.length>0,r.push(...l.map(d=>`artifact:${d}`),...p.slice(0,4).map(d=>`graph:package:${d.label}`)),k&&n.add("Dependency manifests or package entities were observed.");break}case "api":{let l=c.filter(w=>w.kind==="api"||w.kind==="endpoint"||w.kind==="service"&&cr(w)),p=m.filter(w=>or.test(w)),d=a?.contracts?.apis??[],R=(a?.ports??[]).filter(w=>["http","https","grpc"].includes(w.protocol));k=l.length>0||p.length>0||d.length>0||R.length>0,r.push(...l.slice(0,4).map(w=>`graph:${w.kind}:${w.label}`),...p.map(w=>`artifact:${w}`),...d.map(w=>`contract:api:${w.name}:${w.basePath}`),...R.map(w=>`contract:port:${w.name}:${w.protocol}:${w.port}`)),k&&n.add("An API, endpoint, routed artifact, or network contract was observed.");break}case "schema":{let l=c.filter(d=>{if(d.kind==="database")return true;if(d.kind!=="schema")return false;let R=`${d.label} ${JSON.stringify(d.attributes)}`;return /database|migration|sql|prisma|orm/i.test(R)}),p=m.filter(d=>ir.test(d));k=l.length>0||p.length>0,r.push(...l.slice(0,4).map(d=>`graph:${d.kind}:${d.label}`),...p.map(d=>`artifact:${d}`)),k&&n.add("A database, schema, or migration artifact was observed.");break}case "contract":{let l=a?[...a.contracts?.owns??[],...a.contracts?.publishes??[],...a.contracts?.consumes??[],...(a.contracts?.apis??[]).map(d=>d.name)]:[],p=c.filter(d=>["api","protocol"].includes(d.kind));k=l.length>0||p.length>0,r.push(...l.map(d=>`contract:${i.name}:${d}`),...p.slice(0,6).map(d=>`graph:${d.kind}:${d.label}`)),k&&n.add("A shared API, protocol, schema, or authored contract edge was observed.");break}case "derived":k=true;break}k&&t.push(i.name);}return {projects:ue(t,e.model.projects.length),reasons:[...n],signals:ue(r),confidence:e.graph||e.contract?"high":"medium",applicable:t.length>0}}function pr(e,t,r){let n=[];for(let i of t){let c=e.projects.find(l=>l.name===i);if(!c)continue;let m=c.commands.supported.filter(l=>["build","test","lint","format"].includes(l)),a=c.commands.supported.filter(l=>["docs","doctor"].includes(l)),k=r.filter(l=>l.startsWith("artifact:")).map(l=>l.slice(9)).filter(l=>c.importantFiles.includes(l)||l.includes(c.name));n.push(`- **${c.name}** \u2014 runtime \`${c.runtime}\`, framework \`${c.framework}\`, confidence \`${c.confidence}\`.`),n.push(m.length>0?` Registered lifecycle commands: ${m.map(l=>`\`${l}\``).join(", ")}.`:" No project-native build/test command is registered; inspect repository-authored manifests and Graph proofs before running a command."),a.length>0&&n.push(` Registered evidence commands: ${a.map(l=>`\`${l}\``).join(", ")}.`),k.length>0&&n.push(` Relevant artifacts: ${ue(k,6).map(l=>`\`${l}\``).join(", ")}.`);}return n.length>0?n:["- No project boundary was proven; do not infer repository-specific commands or files."]}function ur(e,t){let r=e.applicability==="api"?"api endpoint route service failure":e.applicability==="schema"?"database schema migration persistence":e.applicability==="dependency"?"package dependency manifest lockfile":e.applicability==="contract"?"api protocol published consumed contract":e.applicability==="workspace"?"release pipeline deployment verification":`${e.title.toLowerCase()} manifest command test`;return t.slice(0,8).map(n=>z(`workspace graph search "${r}" --scope project:${n} --limit 12 --json`))}function jt(e){let t=e.model.workspace.name,r=[],n=[];for(let i of [...Qt,...tr(e.model)]){let c=dr({template:i,model:e.model,contract:e.contract??null,graph:e.graph??null}),m={skillId:i.skillId,title:i.title,status:c.applicable?"generated":"suppressed",confidence:c.confidence,reasons:c.reasons.length>0?c.reasons:["No authoritative workspace signal proves this capability is present."],signals:c.signals,scopedProjects:c.projects};if(n.push(m),m.status==="suppressed")continue;let a=m.scopedProjects,k=rr(e.context??null,a),l=nr(e.contract??null,a),p=Zt({template:i,workspaceName:t,scopedProjects:a,verificationCommands:k,contractSummary:l,decision:m,projectEvidence:pr(e.model,a,m.signals),retrievalCommands:ur(i,a)});r.push(Ot({skillId:i.skillId,title:i.title,triggers:i.triggers,requiredReports:[..._t],scopedProjects:a,verificationCommands:k,...X$1(i.skillId)?{promptStem:Y$1[i.skillId]}:{},markdown:p}));}return {skills:r,decisions:n}}async function Nt(e){let t=s.resolve(e.workspacePath),r=[],n=d$1({skills:e.skills.map(a=>({id:a.skillId,path:a.canonicalPath,hash:d$1({markdown:a.markdown})})),decisions:e.decisions??[]}),i=Tt({generatedAt:e.generatedAt,skills:e.skills,inputsHash:n,decisions:e.decisions}),c=new Set(e.skills.map(a=>a.skillId)),m=[];if(e.write){let a=s.join(t,".workspai","skills");if(await h$1.pathExists(a))for(let l of await h$1.readdir(a,{withFileTypes:true})){if(!l.isFile()||!l.name.endsWith(".md"))continue;let p=l.name.slice(0,-3);if(c.has(p))continue;let d=s.join(a,l.name);(await h$1.readFile(d,"utf8")).includes(B)&&(await h$1.remove(d),m.push(p));}for(let l of e.skills){let p=s.join(t,l.canonicalPath);await h$1.ensureDir(s.dirname(p)),await h$1.writeFile(p,l.markdown,"utf8"),r.push(l.canonicalPath);}let k=s.join(t,b$2);await h$1.ensureDir(s.dirname(k)),await h$1.writeJson(k,i,{spaces:2}),r.push(b$2);}return {skills:e.skills,index:i,writtenPaths:r,removedSkillIds:m.sort()}}function Lt(e){return ["## Operational skills (canonical)","","Read workspace-native playbooks from `.workspai/skills/` before generic repo scans. Legacy `.rapidkit/skills/` playbooks are read only when already present from older workspaces:","",...e.skills.map(r=>`- \`${r.path}\` \u2014 ${r.title} (\`${r.skillId}\`)`),"","Regenerate:","","```bash",z("workspace agent-sync --write --refresh-context"),"```",""].join(`
|
|
4
4
|
`)}var gr={"workspai-diagnose-api-failure":A,"workspai-release-readiness":E},Je="## Workspace verification (hydrated)";function mr(e){let t=[Je,"","Verification commands for this workspace:","",...e.verificationCommands.length?e.verificationCommands.map(r=>`- \`${r}\``):["- `npx workspai workspace verify --json`"]];return e.scopedProjects.length>0&&t.push("","Scoped projects:","",...e.scopedProjects.map(r=>`- ${r}`)),t.push(""),t.join(`
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import u from'fs';import a from'path';function N(n){try{let t=JSON.parse(u.readFileSync(a.join(n,"package.json"),"utf8"));return typeof t.packageManager!="string"?null:t.packageManager.trim().match(/^(npm|pnpm|yarn|bun)(?:@|$)/)?.[1]??null}catch{return null}}function x(n){let t=N(n);return t||(u.existsSync(a.join(n,"bun.lock"))||u.existsSync(a.join(n,"bunfig.toml"))?"bun":u.existsSync(a.join(n,"pnpm-lock.yaml"))?"pnpm":u.existsSync(a.join(n,"yarn.lock"))?"yarn":u.existsSync(a.join(n,"package-lock.json"))?"npm":u.existsSync(a.join(n,"pnpm-workspace.yaml"))?"pnpm":"npm")}function G(n,t,e=x(n)){return e==="npm"?`npm run ${t}`:`${e} run ${t}`}function V(n,t=x(n)){return `${t} install`}var C="polyglot-lifecycle-plan.v1",M=new Set([".git",".workspai",".rapidkit",".venv","bin","build","dist","node_modules","obj","target","third_party","vendor","fixture","fixtures","__fixtures__","testdata"]);function h(n,t){return a.relative(n,t).split(a.sep).join("/")||"."}function A(n,t){let e=[],r=(o,l)=>{if(l>t)return;let g=[];try{g=u.readdirSync(o,{withFileTypes:true});}catch{return}for(let f of g.sort((i,p)=>i.name.localeCompare(p.name))){let i=a.join(o,f.name);if(f.isDirectory()){M.has(f.name)||r(i,l+1);continue}f.isFile()&&(["package.json","deno.json","deno.jsonc","pyproject.toml","go.mod","Cargo.toml","pom.xml","build.gradle","build.gradle.kts","build.sbt","deps.edn","composer.json","Gemfile","mix.exs","CMakeLists.txt","meson.build"].includes(f.name)||/\.(?:cs|fs|vb)proj$/i.test(f.name))&&e.push(i);}};return r(n,0),e}function O(n,t){let e=h(n,t).toLowerCase().split("/"),r=e.findIndex(o=>["test","tests","spec","specs","e2e","integration","integration-tests","eval","evals","bench","benchmark","benchmarks","benchmark-app","benchmark-apps"].includes(o));return r<0?false:e.length-r>2}function E(n){if(a.basename(n)!=="package.json")return true;try{let t=a.dirname(n),e=JSON.parse(u.readFileSync(n,"utf8")),r=l=>{let g=e[l];return !!(g&&typeof g=="object"&&Object.keys(g).length>0)},o=e.scripts&&typeof e.scripts=="object"?e.scripts:{};return ["dependencies","devDependencies","optionalDependencies","peerDependencies"].some(r)||["preinstall","install","postinstall","prepare","init","test","build","start"].some(l=>typeof o[l]=="string")||["package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"].some(l=>u.existsSync(a.join(t,l)))||P(n).length>0||u.existsSync(a.join(t,"pnpm-workspace.yaml"))}catch{return true}}function B(n,t){let e=a.basename(t);return e!=="build.gradle"&&e!=="build.gradle.kts"||a.dirname(t)===n?false:u.existsSync(a.join(n,"settings.gradle"))||u.existsSync(a.join(n,"settings.gradle.kts"))}function j(n,t){let e=n.match(new RegExp(`^\\s*${t}\\s*=\\s*\\[([\\s\\S]*?)\\]`,"m"));return e?.[1]?[...e[1].matchAll(/["']([^"']+)["']/g)].map(r=>r[1]??""):[]}function P(n){try{let t=JSON.parse(u.readFileSync(n,"utf8"));if(Array.isArray(t.workspaces))return t.workspaces.filter(e=>typeof e=="string");if(t.workspaces&&typeof t.workspaces=="object"&&!Array.isArray(t.workspaces)){let e=t.workspaces.packages;return Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}}catch{}return []}function _(n){if(!u.existsSync(n))return [];try{let t=u.readFileSync(n,"utf8"),e=t.match(/^packages\s*:\s*\[([^\]]*)\]/m)?.[1];return e!==void 0?[...e.matchAll(/["']([^"']+)["']/g)].map(o=>o[1]??""):[...(t.match(/^packages\s*:\s*\n((?:^[ \t]+-.*\n?)*)/m)?.[1]??"").matchAll(/^[ \t]+-[ \t]+["']?([^"'#\n]+?)["']?[ \t]*$/gm)].map(o=>(o[1]??"").trim())}catch{return []}}function S(n,t){let e=t.replace(/^\.\//,"").replace(/\/$/,""),r="^";for(let o=0;o<e.length;o+=1){let l=e[o]??"";l==="*"&&e[o+1]==="*"?(r+=".*",o+=1):l==="*"?r+="[^/]*":l==="?"?r+="[^/]":r+=l.replace(/[|\\{}()[\]^$+?.]/g,"\\$&");}return new RegExp(`${r}$`).test(n)}function F(n,t){let e=h(n.root,t);return e==="."||e.startsWith("../")||!n.patterns.some(o=>!o.startsWith("!")&&S(e,o))?false:!n.exclusions.some(o=>S(e,o))}function I(n){return n.filter(t=>a.basename(t)==="package.json").map(t=>{let e=a.dirname(t),r=[...P(t),..._(a.join(e,"pnpm-workspace.yaml"))];return {root:e,patterns:r.filter(o=>!o.startsWith("!")),exclusions:r.filter(o=>o.startsWith("!")).map(o=>o.slice(1))}}).filter(t=>t.patterns.length>0)}function W(n){return n.filter(t=>a.basename(t)==="Cargo.toml").map(t=>{try{let e=u.readFileSync(t,"utf8");return /^\s*\[workspace\]\s*$/m.test(e)?{root:a.dirname(t),patterns:j(e,"members"),exclusions:j(e,"exclude")}:null}catch{return null}}).filter(t=>!!t?.patterns.length)}function w(n,t,e){if(a.basename(n)!==e)return false;let r=a.dirname(n);return t.some(o=>o.root!==r&&F(o,r))}function s(n,t,e="high"){return {stage:n,command:t,confidence:e,preflight:"executable-and-inputs"}}function T(n,t){let e={};try{let l=JSON.parse(t);l.scripts&&typeof l.scripts=="object"&&!Array.isArray(l.scripts)&&(e=l.scripts);}catch{}let r=x(n),o=l=>`${r} run ${l}`;return [s("init",r==="yarn"?"yarn install":`${r} install`),...typeof e.test=="string"?[s("test",o("test"))]:[],...typeof e.build=="string"?[s("build",o("build"))]:[],...typeof e.start=="string"?[s("start",o("start"))]:[]]}function D(n,t){let e=a.basename(t),r=a.dirname(t),o=h(n,r),l=h(n,t),g=l.toLowerCase().split("/"),f=g.some(c=>["example","examples","sample","samples","worked","eval","evals","bench","benchmark","benchmarks","benchmark-app","benchmark-apps"].includes(c))?"example":g.some(c=>["test","tests","e2e","integration","integration-tests"].includes(c))?"test":g.some(c=>["script","scripts","tool","tools","tooling"].includes(c))?"tooling":"production",i="";try{i=u.readFileSync(t,"utf8");}catch{return null}let p,d,m;if(e==="package.json"){let c=u.existsSync(a.join(r,"bun.lock"))||u.existsSync(a.join(r,"bun.lockb"))||u.existsSync(a.join(r,"bunfig.toml"))||u.existsSync(a.join(r,".bunfig.toml"));p=c?"bun":"node",d=c?"bun":"npm",m=T(r,i);}else if(e==="deno.json"||e==="deno.jsonc"){p="deno",d="deno";let c={};try{let y=JSON.parse(i);y.tasks&&typeof y.tasks=="object"&&!Array.isArray(y.tasks)&&(c=y.tasks);}catch{}m=[...typeof c.test=="string"?[s("test","deno task test")]:[s("test","deno test","medium")],...typeof c.build=="string"?[s("build","deno task build")]:[],...typeof c.start=="string"?[s("start","deno task start")]:typeof c.dev=="string"?[s("start","deno task dev","medium")]:[]];}else if(e==="pyproject.toml")p="python",d="python",m=[s("init","python -m pip install -e ."),...u.existsSync(a.join(r,"tests"))||/\[tool\.pytest/i.test(i)?[s("test","python -m pytest")]:[],.../\[build-system\]/.test(i)?[s("build","python -m build","medium")]:[]];else if(e==="go.mod")p="go",d="go",m=[s("init","go mod download"),s("test","go test ./..."),s("build","go build ./...")];else if(e==="Cargo.toml")p="rust",d="cargo",m=[s("init","cargo fetch"),s("test","cargo test"),s("build","cargo build"),...u.existsSync(a.join(r,"src","main.rs"))?[s("start","cargo run")]:[]];else if(e==="pom.xml"){p="java",d="maven";let c=u.existsSync(a.join(r,"mvnw"))?"./mvnw":"mvn";m=[s("init",`${c} dependency:go-offline`),s("test",`${c} test`),s("build",`${c} package`)];}else if(e==="build.gradle"||e==="build.gradle.kts"){p=/(?:kotlin|org\.jetbrains\.kotlin)/i.test(i)?"kotlin":"java",d="gradle";let c=u.existsSync(a.join(r,"gradlew"))?"./gradlew":"gradle";m=[s("init",`${c} dependencies`),s("test",`${c} test`),s("build",`${c} build`)];}else if(e==="build.sbt")p="scala",d="sbt",m=[s("init","sbt update"),s("test","sbt test"),s("build","sbt compile")];else if(e==="deps.edn")p="clojure",d="clojure-cli",m=[s("init","clojure -P"),.../:test\b/.test(i)?[s("test","clojure -X:test","medium")]:[]];else if(/\.(?:cs|fs|vb)proj$/i.test(e)){p="dotnet",d="nuget";let c=f==="test"||/<IsTestProject>\s*true\s*<\/IsTestProject>/i.test(i)||/PackageReference\s+Include=["']Microsoft\.NET\.Test\.Sdk["']/i.test(i);m=[s("init",`dotnet restore ${e}`),...c?[s("test",`dotnet test ${e}`)]:[],s("build",`dotnet build ${e}`)];}else if(e==="composer.json"){p="php",d="composer";let c={};try{let y=JSON.parse(i);y.scripts&&typeof y.scripts=="object"&&!Array.isArray(y.scripts)&&(c=y.scripts);}catch{}m=[s("init","composer install"),...typeof c.test<"u"?[s("test","composer test")]:u.existsSync(a.join(r,"vendor","bin","phpunit"))||u.existsSync(a.join(r,"phpunit.xml"))||u.existsSync(a.join(r,"phpunit.xml.dist"))?[s("test","vendor/bin/phpunit","medium")]:[],...typeof c.build<"u"?[s("build","composer build")]:[],...typeof c.start<"u"?[s("start","composer start")]:[]];}else if(e==="Gemfile"){p="ruby",d="bundler";let c=u.existsSync(a.join(r,"bin","rails")),y=c||/\bgem\s+['\"]rails['\"]/.test(i),v=u.existsSync(a.join(r,"spec"))||/\bgem\s+['\"]rspec(?:-rails)?['\"]/.test(i),$=u.existsSync(a.join(r,"test"));m=[s("init","bundle install"),...$&&y?[s("test","bundle exec rails test")]:v?[s("test","bundle exec rspec")]:u.existsSync(a.join(r,"Rakefile"))?[s("test","bundle exec rake test","medium")]:[],...c?[s("start","bundle exec rails server")]:[]];}else if(e==="mix.exs")p="elixir",d="mix",m=[s("init","mix deps.get"),s("test","mix test"),s("build","mix compile"),.../(?:phoenix|phx\.server)/i.test(i)?[s("start","mix phx.server")]:[]];else if(e==="CMakeLists.txt")p=/(?:\bcxx\b|\bcplusplus\b|\bc\+\+\b)/iu.test(i)?"cpp":"c",d="cmake",m=[s("init","cmake -S . -B build"),s("test","ctest --test-dir build --output-on-failure","medium"),s("build","cmake --build build")];else if(e==="meson.build")p=/(?:cpp|c\+\+)/iu.test(i)?"cpp":"c",d="meson",m=[s("init","meson setup build"),s("test","meson test -C build","medium"),s("build","meson compile -C build")];else return null;return {id:`${p}:${o}:${a.basename(l)}`,runtime:p,ecosystem:d,role:f,root:o,manifest:l,stages:m}}function X(n,t={}){let e=a.resolve(n),r=A(e,Math.max(0,Math.min(t.maxDepth??4,12))),o=I(r),l=W(r),g=r.filter(i=>!O(e,i)).filter(i=>!B(e,i)).filter(i=>E(i)).filter(i=>!w(i,o,"package.json")).filter(i=>!w(i,l,"Cargo.toml")).map(i=>D(e,i)).filter(i=>!!i).filter(i=>t.includeExamples===true||i.role!=="example").sort((i,p)=>i.runtime.localeCompare(p.runtime)||i.root.localeCompare(p.root)||i.manifest.localeCompare(p.manifest)),f=[...new Set(g.map(i=>i.runtime))].sort();return {schemaVersion:C,projectRoot:".",polyglot:f.length>1,runtimes:f,units:g}}
|
|
2
|
+
export{x as a,G as b,V as c,X as d};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {a as a$1,b}from'./chunk-O5XQP5E7.js';import {a as a$2}from'./chunk-7Q7X4X5I.js';import {b as b$1}from'./chunk-AO2ZI42U.js';import {a,h,e}from'./chunk-FE5R6EUV.js';import {t,s}from'./chunk-ODK4LCEL.js';import y from'path';import {existsSync}from'fs';import re from'fs-extra';var ie=[{artifactKind:"bootstrap-compliance",cardId:"bootstrap",fileNames:["bootstrap-compliance.latest.json"]},{artifactKind:"doctor-workspace",cardId:"doctor",fileNames:["doctor-remediation-plan-last-run.json","doctor-last-run.json"]},{artifactKind:"analyze",cardId:"analyze",fileNames:["analyze-last-run.json"]},{artifactKind:"readiness",cardId:"readiness",fileNames:["release-readiness-last-run.json"]},{artifactKind:"pipeline",cardId:"pipeline",fileNames:["pipeline-last-run.json"]},{artifactKind:"workspace-run",cardId:"workspaceRun",fileNames:["workspace-run-last.json"]},{artifactKind:"workspace-verify",cardId:"workspaceVerify",fileNames:["workspace-verify-last-run.json"]}];function f(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function w(e){return Array.isArray(e)?e.filter(i=>typeof i=="string"&&i.trim().length>0):[]}function P(e){return [...new Set(e.map(i=>i.trim()).filter(Boolean))]}function G(e){return (e.notes.includes("Doctor finding status: blocking")?16:0)+(e.transaction?8:0)+(e.operation?4:0)+(e.invocation?2:0)+(e.strategy?.length?1:0)}function oe(e){let i=G(e.incoming)>G(e.existing),r=structuredClone(i?e.incoming:e.existing),o=i?e.existing:e.incoming,t=o.sourceStepId;return r.order=e.existing.order,r.files=P([...r.files,...o.files]),r.notes=P([...r.notes,...o.notes.filter(n=>!n.startsWith("Source Doctor capability:")&&!n.startsWith("Doctor finding status:")),...t?[`Also satisfies Doctor capability: ${t}`]:[]]),r}function ne(e,i,r){return r?i:y.relative(e,i).split(y.sep).join("/")}function D(e){return e.includeAbsolutePaths?e.projectPath:b({workspacePath:e.workspacePath,projectPath:e.projectPath,projectName:e.projectName}).contractRelativePath}function U(e){let i=y.isAbsolute(e.filePath)?y.resolve(e.filePath):y.resolve(e.projectPath,e.filePath);if(e.includeAbsolutePaths)return i;let r=y.relative(e.projectPath,i);return !r||r===".."||r.startsWith(`..${y.sep}`)||y.isAbsolute(r)?void 0:`${D(e)}/${r.split(y.sep).join("/")}`}function ae(e){let i=e?.trim()||"npx workspai bootstrap";if(!/(?:^|\s)--ci(?:\s|$)/.test(i)&&/(?:^|\s)--json(?:\s|$)/.test(i))return i.replace(/(?:^|\s)--json(?:\s|$)/,o=>{let t=o.startsWith(" ")?" ":"",n=o.endsWith(" ")?" ":"";return `${t}--ci --json${n}`}).trim();let r=/(?:^|\s)--ci(?:\s|$)/.test(i)?i:`${i} --ci`;return /(?:^|\s)--json(?:\s|$)/.test(r)?r:`${r} --json`}function M(e,i){return y.basename(e).toLowerCase().replace(/\.cmd$/,"")==="npx"&&i[0]==="workspai"&&!i.includes("--no-install")?["--no-install",...i]:i}function J(e){return {cwd:".",executable:"npx",args:M("npx",["workspai",...e])}}function se(e){return `${JSON.stringify({schemaVersion:s.compatibilityMatrix.schemaVersion,generatedAt:e,source:"workspai workspace remediation-plan",runtimes:{},notes:["Minimal enterprise baseline. Add runtime and toolchain entries as governance matures."]},null,2)}
|
|
2
|
+
`}function ce(e){return `${JSON.stringify({schema_version:"1.0",enabled:false,strategy:"on-demand",artifacts:[],created_at:e,note:"Minimal enterprise baseline. Set enabled: true and add artifact entries to activate mirroring."},null,2)}
|
|
3
|
+
`}function de(e){let i=e.payload,r=w(i.blockers),o=w(i.blockingReasons),t=w(i.failures),n=w(i.reasons),d=w(i.policyViolations),c=f(i.summary),l=w(c?.blockers);if(e.artifactKind==="analyze"){let k=(Array.isArray(i.findings)?i.findings:[]).map(b=>f(b)).filter(b=>!!b).map(b=>String(b.message??b.title??b.id??"").trim()).filter(Boolean);return P([...r,...k,...o])}if(e.artifactKind==="workspace-run"){let p=f(i.stages),k=Object.entries(p??{}).flatMap(([b,s])=>{let a=f(s);return (Array.isArray(a?.projects)?a.projects:[]).map(u=>f(u)).filter(u=>!!u).filter(u=>u.status==="failed"||u.ok===false).map(u=>`${b}: ${String(u.project??u.name??"project")} failed`)});return P([...r,...k,...o])}return P([...r,...o,...t,...n,...d,...l])}function v(e){let i=e.findingId?.trim()||e.sourceStepId?.trim()||e.id,r=e.findingStatus??"blocking",o=e.causalKey?.trim()||[e.cardId,e.projectName??e.scope??"workspace",i].map(t=>String(t).trim().toLowerCase()).join(":");return {id:e.id,artifactKind:e.artifactKind,cardId:e.cardId,title:e.title,order:e.order,phase:e.phase,scope:e.scope??"workspace",...e.projectName?{projectName:e.projectName}:{},...e.projectPath?{projectPath:e.projectPath}:{},...e.sourceStepId?{sourceStepId:e.sourceStepId}:{},findingId:i,findingStatus:r,causalKey:o,...e.dependsOn?{dependsOn:e.dependsOn}:{},...e.strategy?{strategy:structuredClone(e.strategy)}:{},...e.transaction?{transaction:structuredClone(e.transaction)}:{},...e.requirements?{requirements:structuredClone(e.requirements)}:{},...e.retryPolicy?{retryPolicy:structuredClone(e.retryPolicy)}:{},status:e.status??"ready",mode:e.mode,risk:e.risk,requiresApproval:true,blocker:e.blocker,summary:e.summary,...e.command?{command:e.command}:{},...e.invocation?{invocation:structuredClone(e.invocation)}:{},verifyCommand:e.verifyCommand,cwd:e.cwd??"workspace",files:e.files??[],...e.operation?{operation:e.operation}:{},rollback:e.rollback??(e.operation?{available:true,strategy:"idempotent"}:{available:false,strategy:"none"}),notes:e.notes??[]}}function le(e){return (Array.isArray(e.report.payload.steps)?e.report.payload.steps:[]).flatMap((r,o)=>{let t=f(r),n=typeof t?.id=="string"?t.id.trim():"",d=typeof t?.projectName=="string"?t.projectName.trim():"",c=typeof t?.projectPath=="string"?t.projectPath.trim():"",l=typeof t?.originalCommand=="string"?t.originalCommand.trim():"";if(!t||!n||!d||!c)return [];let p=f(t.studioStatus),k=p?.state==="ready"||p?.state==="review-required"||p?.state==="blocked"||p?.state==="guidance-only"?p.state:"guidance-only",b=t.risk==="safe"||t.risk==="guarded"||t.risk==="invasive"?t.risk:"guarded",s=f(t.preview),a=D({workspacePath:e.workspacePath,projectPath:c,projectName:d,includeAbsolutePaths:e.includeAbsolutePaths}),g=Z({capability:{...t,command:l},absoluteProjectPath:c,includeAbsolutePaths:e.includeAbsolutePaths}),u=H({capability:t,absoluteProjectPath:c,includeAbsolutePaths:e.includeAbsolutePaths}),R=E({operation:t.operation,absoluteProjectPath:c}),h=t.findingStatus==="blocking"||t.findingStatus==="advisory"||t.findingStatus==="informational"?t.findingStatus:"unknown",j=typeof t.diagnosisFindingId=="string"&&t.diagnosisFindingId.trim()?t.diagnosisFindingId.trim():typeof t.issueId=="string"&&t.issueId.trim()?t.issueId.trim():n,x=typeof t.causalKey=="string"&&t.causalKey.trim()?t.causalKey.trim():void 0,m=!!g&&(t.executable===true||t.executableInCurrentEnvironment===true),A=X({strategy:t.strategy,includeAbsolutePaths:e.includeAbsolutePaths}),I=f(t.transaction),C=I?.schemaVersion==="workspai.doctor-dependency-repair-transaction.v1"?structuredClone(I):void 0;return C&&(C.projectPath=a),[v({id:`doctor.${n}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof s?.title=="string"&&s.title.trim()?s.title.trim():`Repair ${d}`,order:e.startOrder+o,phase:typeof t.phase=="string"?t.phase:"doctor-remediation",blocker:typeof s?.summary=="string"&&s.summary.trim()?s.summary.trim():`Doctor remediation is pending for ${d}.`,summary:typeof s?.summary=="string"&&s.summary.trim()?s.summary.trim():`Execute the CLI-authored Doctor step for ${d}.`,mode:m?"run-command":"manual-guidance",risk:b,status:k,...m&&g?{command:g}:{},...m&&u?{invocation:u}:{},...R?{operation:R}:{},verifyCommand:typeof t.verifyCommand=="string"&&t.verifyCommand.trim()?t.verifyCommand.trim():"npx workspai doctor project --json",files:w(t.files).map($=>U({workspacePath:e.workspacePath,projectPath:c,projectName:d,filePath:$,includeAbsolutePaths:e.includeAbsolutePaths})).filter($=>!!$),notes:[`Source Doctor step: ${n}`,`Doctor finding id: ${j}`,`Doctor finding status: ${h}`,...typeof p?.reason=="string"?[p.reason]:[]],scope:"project",projectName:d,projectPath:a,sourceStepId:n,findingId:j,findingStatus:h,causalKey:x,dependsOn:w(t.dependsOn).map($=>`doctor.${$}`),strategy:A,transaction:C,cwd:"project",...f(t.rollback)?.available===true?{rollback:{available:true,strategy:"manual"}}:{}})]})}function Z(e){let i=typeof e.capability.command=="string"?e.capability.command.trim():"";if(e.includeAbsolutePaths&&i)return i;let r=E({operation:e.capability.operation,absoluteProjectPath:e.absoluteProjectPath});if(r)return b$1(r);let o=f(e.capability.invocation),t=typeof o?.executable=="string"?o.executable.trim():"",n=M(t,w(o?.args));if(t)return [t,...n].map(c=>/^[a-zA-Z0-9_./:@=+-]+$/.test(c)?c:JSON.stringify(c)).join(" ");if(!i)return;let d=e.absoluteProjectPath.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return i.replace(new RegExp(`^cd\\s+["']?${d}["']?\\s*&&\\s*`,"i"),"").replaceAll(e.absoluteProjectPath,".")}function H(e){let i=f(e.capability.invocation),r=typeof i?.executable=="string"?i.executable.trim():"",o=w(i?.args);if(!(!r||o.length!==(Array.isArray(i?.args)?i.args.length:0)))return {cwd:e.includeAbsolutePaths?e.absoluteProjectPath:".",executable:r,args:M(r,o)}}function E(e){let i=f(e.operation);if(!i||typeof i.type!="string")return;let r=structuredClone(i);for(let o of ["path","sourcePath"]){let t=r[o];if(typeof t!="string")continue;let n=y.isAbsolute(t)?y.relative(e.absoluteProjectPath,t):t;if(!n||n===".."||n.startsWith(`..${y.sep}`)||y.isAbsolute(n))return;r[o]=n.split(y.sep).join("/");}return r}function X(e){if(!Array.isArray(e.strategy))return;let i=structuredClone(e.strategy);if(!e.includeAbsolutePaths)for(let r of i)r.invocation&&(r.invocation.cwd=".");return i}function pe(e){let i=Array.isArray(e.report.payload.projects)?e.report.payload.projects:e.report.payload.project?[e.report.payload.project]:[],r=new Set,o=[];for(let t of i){let n=f(t);if(!n)continue;let d=typeof n.name=="string"?n.name.trim():"",c=typeof n.path=="string"?n.path.trim():"";if(!d||!c)continue;let l=Array.isArray(n.repairCapabilities)?n.repairCapabilities:Array.isArray(n.probes)?n.probes.map(s=>f(s)?.repairCapability).filter(s=>s!==void 0):[],p=new Map,k=new Map,b=f(n.diagnosis);for(let s of Array.isArray(b?.findings)?b.findings:[]){let a=f(s),g=f(a?.repair),u=typeof g?.capabilityId=="string"?g.capabilityId.trim():"",R=typeof a?.id=="string"?a.id.trim():"",h=typeof a?.causalKey=="string"?a.causalKey.trim():"",j=a?.status==="blocking"||a?.status==="advisory"||a?.status==="informational"||a?.status==="unknown"?a.status:"unknown";u&&R&&h&&k.set(u,{findingId:R,causalKey:h,findingStatus:j});}for(let s of Array.isArray(n.probes)?n.probes:[]){let a=f(s),g=f(a?.repairCapability),u=typeof g?.id=="string"?g.id.trim():"";u&&p.set(u,a?.status==="fail"?"blocking":"advisory");}for(let s of l){let a=f(s),g=typeof a?.id=="string"?a.id.trim():"";if(!a||!g)continue;let u=`${d}:${g}`;if(r.has(u))continue;r.add(u);let R=a.risk==="safe"||a.risk==="guarded"||a.risk==="invasive"?a.risk:"guarded",h=Z({capability:a,absoluteProjectPath:c,includeAbsolutePaths:e.includeAbsolutePaths}),j=H({capability:a,absoluteProjectPath:c,includeAbsolutePaths:e.includeAbsolutePaths}),x=E({operation:a.operation,absoluteProjectPath:c}),m=a.status==="available"&&!!h,A=f(a.transaction),I=A?.schemaVersion==="workspai.doctor-dependency-repair-transaction.v1"?structuredClone(A):void 0,C=k.get(g),$=C?.findingStatus??p.get(g)??(I?"blocking":"advisory");I&&(I.projectPath=D({workspacePath:e.workspacePath,projectPath:c,projectName:d,includeAbsolutePaths:e.includeAbsolutePaths}));let Y=X({strategy:a.strategy,includeAbsolutePaths:e.includeAbsolutePaths}),ee=w(a.files).map(S=>U({workspacePath:e.workspacePath,projectPath:c,projectName:d,filePath:S,includeAbsolutePaths:e.includeAbsolutePaths})).filter(S=>!!S),W=v({id:`doctor.${d}.${g}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof a.title=="string"&&a.title.trim()?a.title.trim():`Repair ${d}`,order:e.startOrder+o.length,phase:I?"dependency-remediation":"doctor-remediation",blocker:typeof a.reason=="string"&&a.reason.trim()?a.reason.trim():`Doctor remediation is pending for ${d}.`,summary:typeof a.reason=="string"&&a.reason.trim()?a.reason.trim():`Execute the Doctor-authored repair capability for ${d}.`,mode:m?a.canEditFiles===true?"edit-file":"run-command":"manual-guidance",risk:R,status:m?"ready":a.status==="manual"?"guidance-only":"blocked",...h?{command:h}:{},...j?{invocation:j}:{},verifyCommand:typeof a.verifyCommand=="string"&&a.verifyCommand.trim()?a.verifyCommand.trim():"npx workspai doctor project --json",files:ee,notes:[`Source Doctor capability: ${g}`,`Doctor finding status: ${$}`,...w(a.limitations)],scope:"project",projectName:d,projectPath:D({workspacePath:e.workspacePath,projectPath:c,projectName:d,includeAbsolutePaths:e.includeAbsolutePaths}),sourceStepId:g,findingId:C?.findingId??(typeof a.issueId=="string"&&a.issueId.trim()?a.issueId.trim():g),findingStatus:$,causalKey:C?.causalKey,strategy:Y,transaction:I,cwd:"project",...x?{operation:x,rollback:{available:true,strategy:"manual"}}:{}}),O=h?o.findIndex(S=>S.projectName===d&&S.command===h&&S.cwd==="project"):-1;if(O>=0){o[O]=oe({existing:o[O],incoming:W});continue}o.push(W);}}return o}function me(e){let i=[],r=ae("npx workspai bootstrap --json");for(let o of e.blockers)o.includes("profile.enterprise.ci")&&i.push(v({id:"bootstrap.enterprise-ci",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Run bootstrap in deterministic CI mode",order:10,phase:"bootstrap-preflight",blocker:o,summary:"Enterprise bootstrap compliance requires --ci for deterministic execution.",mode:"run-command",risk:"safe",command:r,verifyCommand:r})),o.includes("profile.enterprise.compatibility-matrix")&&i.push(v({id:"bootstrap.compatibility-matrix",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Create enterprise compatibility matrix baseline",order:20,phase:"bootstrap-config",blocker:o,summary:"Create the missing compatibility matrix baseline without overwriting user data.",mode:"edit-file",risk:"safe",verifyCommand:r,files:[t.compatibilityMatrix],operation:{type:"file-create",path:t.compatibilityMatrix,content:se(e.generatedAt),overwrite:false}})),o.includes("profile.enterprise.mirror-config")&&i.push(v({id:"bootstrap.mirror-config",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Create enterprise mirror config baseline",order:30,phase:"bootstrap-config",blocker:o,summary:"Create the missing mirror configuration baseline without enabling mirroring.",mode:"edit-file",risk:"safe",verifyCommand:r,files:[".workspai/mirror-config.json"],operation:{type:"file-create",path:".workspai/mirror-config.json",content:ce(e.generatedAt),overwrite:false}}));return i}function ue(e){let i=Array.isArray(e.report.payload.steps)?e.report.payload.steps:[],r=[],o=new Map;for(let t of i){let n=f(t),d=f(n?.command),c=typeof n?.id=="string"?n.id.trim():"",l=typeof n?.project=="string"?n.project.trim():"",p=typeof n?.status=="string"?n.status:"",k=typeof d?.display=="string"?d.display.trim():"",b=n?.required===true;if(!c.startsWith("project.")||!l||!b||p!=="fail"&&p!=="missing"||!/^npx\s+workspai\s+workspace\s+run\s+/i.test(k))continue;let s=c.split(".").at(-1)??"stage",a=`workspaceVerify.${c}`,g=o.get(l),u=/(?:^|\s)--no-gates(?:\s|$)/.test(k)?k:`${k} --no-gates`;r.push(v({id:a,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof n.label=="string"&&n.label.trim()?n.label.trim():`Run ${s} for ${l}`,order:e.startOrder+r.length,phase:"fleet-run",blocker:typeof n.message=="string"&&n.message.trim()?n.message.trim():`${s} evidence is not current for ${l}.`,summary:`Produce fresh ${s} evidence for ${l} without re-entering the blocked aggregate gates.`,mode:"run-command",risk:s==="start"?"guarded":"safe",status:"ready",command:u,verifyCommand:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json",scope:"project",projectName:l,projectPath:l,sourceStepId:c,...g?{dependsOn:[g]}:{},cwd:"workspace",notes:[`Source Workspace Verify step: ${c}`,"Aggregate verification must run only after this project evidence producer completes."]})),o.set(l,a);}return r}var T={python:["python3","python","py"],node:["node"],go:["go"],java:["java"],dotnet:["dotnet"],rust:["cargo"],php:["php"]};async function fe(e,i,r){for(let o of T[e]??[e])if(r?await r(o,i):await a$2({executable:o,cwd:i}))return o}async function ge(e){let i=P(e.blockers.flatMap(o=>{let t=o.match(/(?:project runtimes?|workspace)\s*\(([^)]+)\)\s+(?:is|are) not pinned/i);return t?.[1]?t[1].split(",").map(n=>n.trim().toLowerCase()).filter(n=>/^(python|node|go|java|dotnet|rust|php)$/.test(n)):[]})),r=[];for(let o of i){let t=T[o]??[o],n=await fe(o,e.workspacePath,e.toolAvailable),d=`environment.runtime.${o}`,c=`readiness.toolchain.${o}.setup`,l=e.blockers.find(p=>p.toLowerCase().includes(`(${o})`))??`The ${o} runtime is not pinned in the canonical workspace toolchain.`;n||r.push(v({id:d,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Provide the ${o} host runtime`,order:e.startOrder+r.length,phase:"host-prerequisite",blocker:`No launchable ${o} runtime is available in the current environment.`,summary:`Install or configure ${t.join(" or ")} outside Workspai, then refresh the remediation plan.`,mode:"manual-guidance",risk:"safe",status:"guidance-only",verifyCommand:`npx workspai setup ${o} --json`,requirements:[{kind:"executable",id:`executable:${o}`,status:"missing",executable:t.join("|"),message:`A launchable ${t.join(" or ")} executable must be visible to Workspai.`}],retryPolicy:{sameGeneration:"forbidden",resumeWhen:"environment-changed"},notes:["`workspai setup` detects and pins an existing runtime; it does not install host software."]})),r.push(v({id:c,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Pin ${o} in the workspace toolchain`,order:e.startOrder+r.length,phase:"toolchain-reconciliation",blocker:l,summary:`Detect and persist the current ${o} runtime in the canonical workspace toolchain lock.`,mode:"run-command",risk:"safe",status:n?"ready":"blocked",command:`npx workspai setup ${o} --json`,invocation:J(["setup",o,"--json"]),verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",dependsOn:n?void 0:[d],requirements:[{kind:"executable",id:`executable:${o}`,status:n?"satisfied":"missing",executable:n??t.join("|"),message:n?`Runtime prerequisite is launchable: ${n}.`:`Runtime prerequisite is unavailable: ${t.join(" or ")}.`},...n?[]:[{kind:"action",id:`action:${d}`,status:"pending",actionId:d,message:"The host runtime prerequisite must be resolved first."}]],retryPolicy:n?{sameGeneration:"allowed",resumeWhen:"immediate"}:{sameGeneration:"forbidden",resumeWhen:"environment-changed"},notes:["Run from the workspace root so the canonical toolchain.lock is updated."]})),r.push(v({id:`readiness.toolchain.${o}.bootstrap`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Reconcile the ${o} workspace foundation`,order:e.startOrder+r.length,phase:"toolchain-reconciliation",blocker:`The ${o} runtime pin must be reconciled with the workspace foundation.`,summary:"Refresh the workspace foundation after the runtime pin is written.",mode:"run-command",risk:"guarded",status:n?"ready":"blocked",command:"npx workspai bootstrap --ci --json",invocation:J(["bootstrap","--ci","--json"]),verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",dependsOn:[c],requirements:[{kind:"action",id:`action:${c}`,status:"pending",actionId:c,message:`The ${o} toolchain pin must complete first.`}],retryPolicy:{sameGeneration:n?"allowed":"forbidden",resumeWhen:n?"dependencies-complete":"environment-changed"}}));}return r}function ye(e){if(e.report.artifactKind==="readiness"&&/dependenc(?:y|ies).*vulnerabil|vulnerabil.*dependenc(?:y|ies)|security audit/i.test(e.blocker))return v({id:`${e.report.cardId}.doctor-owner.${e.order}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:"Resolve dependency vulnerability through Doctor",order:e.order,phase:"dependency-remediation",blocker:e.blocker,summary:"Release Readiness is the aggregate gate; use the project-scoped Doctor remediation capability that owns this dependency failure.",mode:"verify-before-fix",risk:"guarded",status:"review-required",command:"npx workspai doctor workspace --plan --json",verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",notes:["Read doctor-remediation-plan-last-run.json and execute the matching surface-security-hygiene capability before rerunning Readiness.","Do not treat a Readiness refresh as remediation for a source dependency vulnerability."]});let r={analyze:{title:"Refresh analyze evidence",phase:"analysis",command:"npx workspai analyze --strict --json",verify:"npx workspai analyze --strict --json"},readiness:{title:"Refresh release readiness",phase:"release-readiness",command:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",verify:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json"},pipeline:{title:"Rerun governance pipeline",phase:"governance-pipeline",command:"npx workspai pipeline --json --strict",verify:"npx workspai pipeline --json --strict"},"workspace-run":{title:"Rerun failed workspace stage",phase:"fleet-run",command:e.ciMode?"npx workspai workspace run test --strict --json":"npx workspai workspace run test --json",verify:e.ciMode?"npx workspai workspace run test --strict --json":"npx workspai workspace run test --json"},"workspace-verify":{title:"Refresh workspace verify gate",phase:"verification",command:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json",verify:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json"},"doctor-workspace":{title:"Use Doctor remediation plan",phase:"doctor-remediation",command:"npx workspai doctor workspace --plan --json",verify:"npx workspai doctor workspace --json"}}[e.report.artifactKind]??{title:"Refresh artifact evidence",phase:"evidence-refresh",command:"npx workspai pipeline --json --strict",verify:"npx workspai pipeline --json --strict"};return v({id:`${e.report.cardId}.refresh.${e.order}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:r.title,order:e.order,phase:r.phase,blocker:e.blocker,summary:"No deterministic file operation is available for this artifact yet; refresh the evidence and continue with the card-specific plan.",mode:e.report.artifactKind==="doctor-workspace"?"verify-before-fix":"run-command",risk:"guarded",status:e.report.artifactKind==="doctor-workspace"?"review-required":"ready",command:r.command,verifyCommand:r.verify,notes:e.report.artifactKind==="doctor-workspace"?["Read doctor-remediation-plan-last-run.json for ordered file-level steps."]:[]})}function Q(e){let i=e.transaction?.ecosystem.toLowerCase(),r=y.basename(e.invocation?.executable??"").toLowerCase(),o=`${i??""}:${r}`;if(/(^|:)(python|pip|pip3|poetry|uv)(:|$)/.test(o))return "python";if(/(^|:)(node|npm|pnpm|yarn|bun)(:|$)/.test(o))return "node";if(/(^|:)(go)(:|$)/.test(o))return "go";if(/(^|:)(java|maven|mvn|mvnw|gradle|gradlew)(:|$)/.test(o))return "java";if(/(^|:)(dotnet|nuget)(:|$)/.test(o))return "dotnet";if(/(^|:)(rust|cargo|rustc)(:|$)/.test(o))return "rust";if(/(^|:)(php|composer)(:|$)/.test(o))return "php"}function be(e,i){let r=i.invocation?.cwd??e;return y.isAbsolute(r)?r:y.resolve(e,r)}function he(e,i){let r=Q(e);if(r&&T[r]?.includes(y.basename(i)))return `environment.runtime.${r}`;let o=(e.projectName??"workspace").replace(/[^a-zA-Z0-9.-]+/g,"-"),t=y.basename(i).replace(/[^a-zA-Z0-9.-]+/g,"-");return `environment.executable.${o}.${t}`}async function ke(e){let i=new Map,r=new Map(e.actions.map(t=>[t.id,t]));for(let t of e.actions){if(!t.invocation||t.status==="guidance-only")continue;let n=be(e.workspacePath,t),d=e.toolAvailable?await e.toolAvailable(t.invocation.executable,n):await a$2({executable:t.invocation.executable,cwd:n}),c={kind:"executable",id:`executable:${t.invocation.executable}`,status:d?"satisfied":"missing",executable:t.invocation.executable,message:d?`Required executable is launchable: ${t.invocation.executable}.`:`Required executable is unavailable: ${t.invocation.executable}.`};if(t.requirements=[...(t.requirements??[]).filter(p=>p.id!==c.id),c],d)continue;let l=he(t,t.invocation.executable);!r.has(l)&&!i.has(l)&&i.set(l,v({id:l,artifactKind:t.artifactKind,cardId:"environment",title:`Provide ${y.basename(t.invocation.executable)}`,order:0,phase:"host-prerequisite",blocker:`The required executable ${t.invocation.executable} is unavailable.`,summary:"Install or configure the required executable outside Workspai, then refresh the plan.",mode:"manual-guidance",risk:"safe",status:"guidance-only",verifyCommand:t.verifyCommand,scope:t.scope,projectName:t.projectName,projectPath:t.projectPath,requirements:[c],retryPolicy:{sameGeneration:"forbidden",resumeWhen:"environment-changed"},notes:["The CLI does not install host runtimes or system package managers implicitly."]})),t.status="blocked",t.dependsOn=P([...t.dependsOn??[],l]),t.requirements.push({kind:"action",id:`action:${l}`,status:"pending",actionId:l,message:"Resolve the executable prerequisite and generate fresh evidence first."}),t.retryPolicy={sameGeneration:"forbidden",resumeWhen:"environment-changed"},t.notes.push("This action is not eligible in the current plan generation because its executable precondition failed.");}let o=[...i.values(),...e.actions];return o.forEach((t,n)=>{t.order=n+1;}),o}function Ae(e){let i=new Set(e.map(r=>r.id));for(let r of e){if(!r.transaction)continue;let o=Q(r);if(!o)continue;let t=`readiness.toolchain.${o}.bootstrap`;i.has(t)&&(r.dependsOn=P([...r.dependsOn??[],t]),r.requirements=[...r.requirements??[],{kind:"action",id:`action:${t}`,status:"pending",actionId:t,message:`The canonical ${o} workspace foundation must be reconciled first.`}],r.status==="ready"&&(r.retryPolicy={sameGeneration:"allowed",resumeWhen:"dependencies-complete"}));}}function we(e){let i=e.filter(t=>t.status==="ready"&&(t.dependsOn?.length??0)===0).map(t=>t.id),r=e.filter(t=>t.status==="blocked").map(t=>t.id),o=e.find(t=>t.status==="guidance-only")?.id??null;return {nextActionId:i[0]??o,eligibleActionIds:i,blockedActionIds:r}}async function ve(e$1){let i=[a(e$1,".workspai/reports"),e(e$1,".workspai/reports")],r=[],o=new Set;for(let t of ie)for(let n of t.fileNames){let d=(await Promise.all(i.map(c=>y.join(c,n)))).find(c=>existsSync(c));if(!(!d||o.has(`${t.artifactKind}:${n}`))){o.add(`${t.artifactKind}:${n}`);try{let c=await re.readJSON(d),l=f(c);if(!l)continue;r.push({artifactKind:t.artifactKind,cardId:t.cardId,fileName:n,absolutePath:d,payload:l});break}catch{r.push({artifactKind:t.artifactKind,cardId:t.cardId,fileName:n,absolutePath:d,payload:{blockers:[`${t.artifactKind}: report exists but could not be parsed.`]}});break}}}return r}async function Ne(e){let i=y.resolve(e.workspacePath),r=e.includeAbsolutePaths===true,o=e.ciMode===true,t=new Date().toISOString(),n=a(i,".workspai/reports"),d=await ve(i),c=[],l=1;for(let s of d){if(s.artifactKind==="doctor-workspace"){let m=Array.isArray(s.payload.steps)?le({report:s,workspacePath:i,includeAbsolutePaths:r,startOrder:l}):pe({report:s,workspacePath:i,includeAbsolutePaths:r,startOrder:l});c.push(...m),l+=m.length;continue}let a=de(s);if(a.length===0)continue;if(s.artifactKind==="bootstrap-compliance"){c.push(...me({blockers:a,generatedAt:t})),l=c.length+1;continue}if(s.artifactKind==="workspace-verify"){let m=ue({report:s,startOrder:l,ciMode:o});if(m.length>0){c.push(...m),l+=m.length;continue}}if(s.artifactKind==="readiness"){let m=await ge({report:s,blockers:a,startOrder:l,ciMode:o,workspacePath:i,toolAvailable:e.toolAvailable});if(m.length>0){c.push(...m),l+=m.length;continue}}let g=c.some(m=>m.transaction?.kind==="dependency-security"),u=s.artifactKind==="readiness"&&a.some(m=>/dependenc(?:y|ies).*vulnerabil|vulnerabil.*dependenc(?:y|ies)|security audit/i.test(m));if(g&&u)continue;let R=a[0],h=ye({report:s,blocker:R,order:l,ciMode:o}),x={readiness:new Set(["bootstrap","doctor"]),pipeline:new Set(["bootstrap","doctor","analyze","readiness"]),workspaceVerify:new Set(["bootstrap","doctor","readiness","workspaceRun"])}[s.cardId];if(s.cardId==="pipeline"){let m=["doctor","analyze","readiness"].find(A=>R.toLowerCase().includes(A));m&&(x=new Set([m]));}if(x){let m=c.filter(A=>x.has(A.cardId)&&A.risk!=="invasive"&&A.status!=="blocked"&&A.status!=="guidance-only").map(A=>A.id);m.length>0&&(h.dependsOn=P([...h.dependsOn??[],...m]),h.notes.push("This aggregate gate must run after its contract-owned upstream remediation actions."));}a.length>1&&h.notes.push(...a.slice(1,8).map(m=>`Related blocker: ${m}`)),c.push(h),l+=1;}Ae(c);let p=await ke({actions:c,workspacePath:i,toolAvailable:e.toolAvailable}),k=we(p),b={safe:p.filter(s=>s.risk==="safe").length,guarded:p.filter(s=>s.risk==="guarded").length,invasive:p.filter(s=>s.risk==="invasive").length};return {schemaVersion:a$1,generatedAt:t,workspace:{name:y.basename(i),...r?{path:i}:{}},source:{command:"workspace remediation-plan",reportsDir:ne(i,n,r),includeAbsolutePaths:r,ciMode:o},summary:{artifactsScanned:d.length,cardsCovered:P(p.map(s=>s.cardId)).length,totalActions:p.length,executableActions:p.filter(s=>s.status==="ready").length,blockedActions:p.filter(s=>s.status==="blocked").length,guidanceActions:p.filter(s=>s.status==="guidance-only").length,risk:b},execution:k,actions:p}}async function qe(e,i){return h(i,t.artifactRemediationPlan,e)}export{Ne as a,qe as b};
|
|
@@ -2,7 +2,7 @@ import {c}from'./chunk-N4B2M44I.js';import {a}from'./chunk-A5FBGRJA.js';import {
|
|
|
2
2
|
`);}async function se(e,r){let t=n.dirname(e);await promises.mkdir(t,{recursive:true});let o=`${e}.${process.pid}.${randomUUID()}.tmp`;try{await promises.writeFile(o,r);let a=await promises.open(o,"r");try{await ae(a);}finally{await a.close();}try{await promises.rename(o,e);}catch(s){let i=s.code;if(i!=="EEXIST"&&i!=="EPERM")throw s;await le.move(o,e,{overwrite:true});}}finally{await promises.rm(o,{force:true}).catch(()=>{});}}async function Z(e){try{return {exists:true,content:await promises.readFile(e)}}catch(r){if(r.code==="ENOENT")return {exists:false};throw r}}async function ee(e,r){if(!r.exists){await promises.rm(e,{force:true});return}await se(e,r.content);}async function we(e,r){let t=n.join(e,"workspaces.json.lock"),o=randomUUID();await promises.mkdir(e,{recursive:true});let a=Date.now(),s;for(;!s;)try{s=await promises.open(t,"wx"),await s.writeFile(`${JSON.stringify({pid:process.pid,lockId:o,createdAt:new Date().toISOString()})}
|
|
3
3
|
`),await ae(s);}catch(i){if(i.code!=="EEXIST")throw i;let c=await promises.stat(t).catch(()=>null);if(c&&Date.now()-c.mtimeMs>de){let d=await promises.readFile(t,"utf8").then(g=>JSON.parse(g)).catch(()=>null),u=Number(d?.pid),f=false;if(Number.isInteger(u)&&u>0)try{process.kill(u,0),f=true;}catch(g){f=g.code==="EPERM";}if(!f){await promises.rm(t,{force:true}).catch(()=>{});continue}}if(Date.now()-a>me)throw new Error(`Timed out waiting for workspace registry lock: ${t}`);await new Promise(d=>setTimeout(d,25));}try{return await r()}finally{await s.close().catch(()=>{}),await promises.readFile(t,"utf8").then(c=>JSON.parse(c).lockId===o).catch(()=>false)&&await promises.rm(t,{force:true}).catch(()=>{});}}async function S(e){let r$1=q(),t=n.join(r$1,"workspaces.json"),o=n.join(r(),"workspaces.json"),a=[...new Set(s$1())];return we(r$1,async()=>{let[s,i]=await Promise.all([Z(t),Z(o)]),c=await oe(a);await e(c);let d=I(c);try{await X(t,d),await X(o,d);}catch(u){let g=(await Promise.allSettled([ee(t,s),ee(o,i)])).filter(k=>k.status==="rejected").map(k=>k.reason);throw g.length>0?new AggregateError([u,...g],"Workspace registry transaction failed and could not be fully restored"):u}return d})}async function ie(e,r){let t=a(e);await S(o=>{let a=o.workspaces.find(s=>s.path===t);if(a){a.name=r,a.mode=a.mode||"full",a.projects=Array.isArray(a.projects)?a.projects:[];return}o.workspaces.push({name:r,path:t,mode:"full",projects:[]});});}async function He(e){let r=a(e),o=(await oe()).workspaces.find(a=>a.path===r);return o?{...o,projects:o.projects.map(a=>({...a}))}:null}async function Ke(e,r){let t=a(e);await S(o=>{let a=o.workspaces.findIndex(i=>i.path===t);if(!r){a>=0&&o.workspaces.splice(a,1);return}let s=G(r);a>=0?o.workspaces[a]=s:o.workspaces.push(s);});}async function qe(e){let r=a(e);await S(t=>{t.workspaces=t.workspaces.filter(o=>o.path!==r);});}async function he(e,r){try{await ie(e,r);}catch{console.warn(p.gray("Note: Could not register workspace in shared registry"));}}async function Qe(e,r=false){let t=a(e),o={workspacePath:t,workspaceFound:false,added:[],skipped:0};try{let a$1=await z(),s=a$1.workspaces.find(k=>k.path===t);if(!s){if(await he(t,n.basename(n.resolve(e))),a$1=await z(),s=a$1.workspaces.find(k=>k.path===t),!s)return r||console.log("\u26A0\uFE0F Workspace could not be registered in registry"),o;r||console.log("\u2714 Registered workspace in shared registry");}Array.isArray(s.projects)||(s.projects=[]);let i=0,c=0,d=[],u$1=[],f=[e],g=new Set;for(;f.length>0;){let k=f.shift();if(!k||g.has(k))continue;g.add(k);let w=await promises.readdir(k,{withFileTypes:true});for(let h of w){if(!h.isDirectory()||h.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(h.name))continue;let v=n.join(k,h.name),y=a(v);try{let x=false;for(let P of [...u(y,"context.json"),...u(y,"project.json")])try{await promises.access(P),x=true;break}catch{}if(x){let P=n.basename(y),m=s.projects.some($=>$.path===y);u$1.push({name:P,path:y}),m?c++:(s.projects.push({name:P,path:y}),i++,d.push(y),r||console.log(`\u2714 Added: ${n.relative(e,y)}`));continue}}catch{}f.push(v);}}return await S(k=>{let w=k.workspaces.find(y=>y.path===t);if(!w)return;let h=`${t}${n.sep}`,v=(w.projects||[]).filter(y=>y.path!==t&&!y.path.startsWith(h));w.projects=G({...w,projects:[...v,...u$1]}).projects;}),i>0?r||console.log(`
|
|
4
4
|
\u2705 Synced ${i} project(s) to registry`):r||console.log(`
|
|
5
|
-
\u2705 All projects already registered (${c} found)`),{workspacePath:t,workspaceFound:true,added:d,skipped:c}}catch(a){return r||console.error("\u274C Failed to sync projects:",a.message),o}}async function ye(e,r,t){let o=a(e),a$1=a(t);await S(s=>{let i=s.workspaces.find(u=>u.path===o);if(!i)throw new Error(`Workspace is not registered: ${o}`);i.projects=Array.isArray(i.projects)?i.projects:[];let c=i.projects.findIndex(u=>u.path===a$1||u.name===r),d={name:r,path:a$1};c>=0?i.projects[c]=d:i.projects.push(d);});}async function Xe(e,r,t){try{await ye(e,r,t);}catch{}}async function Ze(e,r){let t=N("Creating Workspai workspace...").start();try{await promises.mkdir(e,{recursive:true}),await promises.mkdir(n.join(e,".workspai"),{recursive:true});let o={workspace_name:r.name,author:r.author,rapidkit_version:h(),created_at:new Date().toISOString(),type:"workspace"};await promises.writeFile(n.join(e,".workspai","config.json"),JSON.stringify(o,null,2));let{syncWorkspaceFoundationFiles:a}=await import('./create-
|
|
5
|
+
\u2705 All projects already registered (${c} found)`),{workspacePath:t,workspaceFound:true,added:d,skipped:c}}catch(a){return r||console.error("\u274C Failed to sync projects:",a.message),o}}async function ye(e,r,t){let o=a(e),a$1=a(t);await S(s=>{let i=s.workspaces.find(u=>u.path===o);if(!i)throw new Error(`Workspace is not registered: ${o}`);i.projects=Array.isArray(i.projects)?i.projects:[];let c=i.projects.findIndex(u=>u.path===a$1||u.name===r),d={name:r,path:a$1};c>=0?i.projects[c]=d:i.projects.push(d);});}async function Xe(e,r,t){try{await ye(e,r,t);}catch{}}async function Ze(e,r){let t=N("Creating Workspai workspace...").start();try{await promises.mkdir(e,{recursive:true}),await promises.mkdir(n.join(e,".workspai"),{recursive:true});let o={workspace_name:r.name,author:r.author,rapidkit_version:h(),created_at:new Date().toISOString(),type:"workspace"};await promises.writeFile(n.join(e,".workspai","config.json"),JSON.stringify(o,null,2));let{syncWorkspaceFoundationFiles:a}=await import('./create-7CWWGDXQ.js');await a(e,{workspaceName:r.name,installMethod:"venv",writeMarker:true,writeGitignore:false,onlyIfMissing:true});let s=$e();await promises.writeFile(n.join(e,"rapidkit"),s),await promises.chmod(n.join(e,"rapidkit"),493);let i=je();await promises.writeFile(n.join(e,"rapidkit.cmd"),i);let c=ve(r.name);await promises.writeFile(n.join(e,"README.md"),c),await promises.writeFile(n.join(e,".gitignore"),`# Workspai workspace
|
|
6
6
|
.env
|
|
7
7
|
.env.*
|
|
8
8
|
!.env.example
|
|
@@ -17,7 +17,7 @@ Thumbs.db
|
|
|
17
17
|
|
|
18
18
|
# Logs
|
|
19
19
|
*.log
|
|
20
|
-
`),await _e(e),t.succeed("Workspace created!"),r.skipGit||await re(e,N(),"Initial commit: Workspai workspace"),await ie(e,r.name);let{publishWorkspaceRegistrySummary:u}=await import('./workspace-registry-summary-
|
|
20
|
+
`),await _e(e),t.succeed("Workspace created!"),r.skipGit||await re(e,N(),"Initial commit: Workspai workspace"),await ie(e,r.name);let{publishWorkspaceRegistrySummary:u}=await import('./workspace-registry-summary-WKENOFEA.js');await u(e),console.log(`
|
|
21
21
|
${p.green("\u2728 Workspai workspace created successfully!")}
|
|
22
22
|
|
|
23
23
|
${p.bold("\u{1F4C2} Workspace structure:")}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import {d,b,e}from'./chunk-37SWTS2B.js';import {d as d$2,c as c$1,b as b$1}from'./chunk-CQBM6BBP.js';import {d as d$3}from'./chunk-S5KTATOU.js';import {a}from'./chunk-NMXGSVMD.js';import {q as q$1,z,u as u$1}from'./chunk-SATPH22S.js';import {k,m,g as g$1,f as f$1}from'./chunk-6WOFOOM7.js';import {g}from'./chunk-FE5R6EUV.js';import {p,t}from'./chunk-ODK4LCEL.js';import {a as a$1}from'./chunk-TQEMLBAG.js';import {c,d as d$1}from'./chunk-25AWHAB5.js';import {e as e$1,g as g$2}from'./chunk-RGNCL5OB.js';import {u,q,t as t$1}from'./chunk-VQZ5PI5J.js';import Y from'fs';import f from'path';import W from'chalk';import {execa}from'execa';var lt={"python-fastapi":{runtime:"python",framework:"FastAPI",markers:["pyproject.toml","fastapi"],commands:{init:"python -m pip install -e .",test:"pytest",build:"python -m build",start:"uvicorn main:app --reload"},errorPatterns:{setup:["ModuleNotFoundError","No module named","pip: command not found"],"test-failure":["FAILED","ERROR","test session started"],dependency:["ImportError","missing.*dependency"],runtime:["TypeError","AttributeError","ValueError"],timeout:["timeout","Timeout","timed out"],unknown:[]},healthCheck:{stage:"start",type:"http",value:"http://localhost:8000/docs"},validation:{command:"python -m pip list | grep fastapi",error:"FastAPI not installed"}},"python-django":{runtime:"python",framework:"Django",markers:["manage.py","django"],commands:{init:"python manage.py migrate",test:"python manage.py test",build:"python manage.py collectstatic --noinput",start:"python manage.py runserver 0.0.0.0:8000"},errorPatterns:{setup:["ModuleNotFoundError","ProgrammingError.*migrate"],"test-failure":["FAILED","ERROR","Ran.*test"],dependency:["ImportError","missing.*dependency"],runtime:["DatabaseError","ImproperlyConfigured"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"node-nestjs":{runtime:"node",framework:"NestJS",markers:["package.json","@nestjs/core"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm run start"},errorPatterns:{setup:["npm ERR!","ENOENT","not found"],"test-failure":["Tests.*failed","FAIL","fail.*test"],dependency:["Cannot find module","ERR_MODULE_NOT_FOUND"],runtime:["TypeError","Error: ","ReferenceError"],timeout:["timeout","TIMEOUT"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3}},"node-express":{runtime:"node",framework:"Express",markers:["package.json","express"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm start"},errorPatterns:{setup:["npm ERR!","ENOENT"],"test-failure":["failed","FAIL"],dependency:["Cannot find module"],runtime:["Error","TypeError"],timeout:["timeout"],unknown:[]}},"go-fiber":{runtime:"go",framework:"Fiber",markers:["go.mod","fiber"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found","cannot find","go mod tidy"],"test-failure":["FAIL","--- FAIL"],dependency:["missing.*module"],runtime:["panic","fatal","Error"],timeout:["timeout","context deadline"],unknown:[]},dependencies:["init"]},"go-gin":{runtime:"go",framework:"Gin",markers:["go.mod","gin-gonic"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found"],"test-failure":["FAIL"],dependency:["missing.*module"],runtime:["panic"],timeout:["timeout"],unknown:[]}},"java-springboot":{runtime:"java",framework:"Spring Boot",markers:["pom.xml","build.gradle","spring-boot"],commands:{init:"mvn dependency:go-offline",test:"mvn test",build:"mvn package -DskipTests",start:"mvn spring-boot:run"},errorPatterns:{setup:["\\[ERROR\\]","BUILD FAILURE","missing dependencies"],"test-failure":["\\[ERROR\\] Tests run:","BUILD FAILURE"],dependency:["missing.*dependency"],runtime:["Exception","Error","NullPointerException"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8080}},"php-laravel":{runtime:"php",framework:"Laravel",markers:["composer.json","artisan","app/Models"],commands:{init:"composer install && php artisan migrate:fresh --seed",test:"php artisan test",build:"php artisan config:cache && php artisan route:cache && php artisan view:cache",start:"php artisan serve --host=0.0.0.0 --port=8000"},errorPatterns:{setup:["Composer.*lock","Fatal error","Class.*not found"],"test-failure":["FAILED","Tests.*failed"],dependency:["Class.*not found","require.*failed"],runtime:["Fatal error","Exception","Error"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"php-symfony":{runtime:"php",framework:"Symfony",markers:["composer.json","symfony.lock","bin/console"],commands:{init:"composer install && php bin/console doctrine:database:create",test:"php bin/phpunit",build:"php bin/console cache:clear --env=prod",start:"symfony serve --no-tls"},errorPatterns:{setup:["Composer.*error","Fatal error"],"test-failure":["FAILED","failure"],dependency:["Class.*not found"],runtime:["Fatal error","Exception"],timeout:["timeout"],unknown:[]},dependencies:["init"]},"rust-actix":{runtime:"rust",framework:"Actix-web",markers:["Cargo.toml","actix"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find","failed.*download"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E","thread.*panicked"],timeout:["timeout"],unknown:[]},validation:{command:"cargo --version",error:"Rust/Cargo not installed"}},"rust-axum":{runtime:"rust",framework:"Axum",markers:["Cargo.toml","axum"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"rust-rocket":{runtime:"rust",framework:"Rocket",markers:["Cargo.toml","rocket"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["FAILED"],dependency:["can.t find"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"dotnet-aspnetcore":{runtime:"dotnet",framework:"ASP.NET Core",markers:[".csproj",".sln","Program.cs"],commands:{init:"dotnet restore",test:"dotnet test",build:"dotnet build -c Release",start:"dotnet run"},errorPatterns:{setup:["error CS","CSPROJ.*not found","NuGet.*restore"],"test-failure":["Failed:.*test","FAILED"],dependency:["error NU1101"],runtime:["error CS","Exception"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:5e3}},"elixir-phoenix":{runtime:"elixir",framework:"Phoenix",markers:["mix.exs","phoenix"],commands:{init:"mix setup",test:"mix test",build:"mix compile --all-warnings",start:"mix phx.server"},errorPatterns:{setup:["\\*\\* \\(.*Error\\)","Mix.InstallError"],"test-failure":["\\d+\\sfailed","FAILED"],dependency:["dependencies are not available"],runtime:["\\*\\* \\(","RuntimeError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:4e3},dependencies:["init"]},"ruby-rails":{runtime:"ruby",framework:"Rails",markers:["Gemfile","config/application.rb","bin/rails"],commands:{init:"bundle install && rails db:prepare",test:"rails test",build:"rails assets:precompile",start:"rails server --binding=0.0.0.0 --port=3000"},errorPatterns:{setup:["Bundler::.*Error","Gem::.*Error"],"test-failure":["failures,","error,","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","Exception","NoMethodError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3},dependencies:["init"]},"ruby-sinatra":{runtime:"ruby",framework:"Sinatra",markers:["Gemfile","app.rb","sinatra"],commands:{init:"bundle install",test:"rspec",build:`echo "Sinatra apps don't require build"`,start:"ruby app.rb"},errorPatterns:{setup:["Bundler.*Error","Gem.*Error"],"test-failure":["failure","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","NoMethodError"],timeout:["timeout"],unknown:[]}}},pt={init:{python:["pip install -e .","poetry install","pip install -r requirements.txt"],node:["npm install","pnpm install","yarn install"],go:["go mod download && go mod tidy","go get ./..."],java:["mvn dependency:go-offline","gradle dependencies"],php:["composer install"],rust:["cargo fetch"],dotnet:["dotnet restore"],c:["cmake -S . -B build"],cpp:["cmake -S . -B build"],elixir:["mix deps.get"],ruby:["bundle install"],clojure:["clojure -P"],scala:["sbt update"],kotlin:["./gradlew dependencies","gradle dependencies"],deno:[],bun:["bun install"],"jvm-generic":["mvn dependency:go-offline","gradle dependencies"],unknown:[]},test:{python:["pytest","python -m unittest","python -m pytest"],node:["npm test","npm run test"],go:["go test ./...","make test"],java:["mvn test","gradle test"],php:["php artisan test","phpunit","pest"],rust:["cargo test"],dotnet:["dotnet test"],c:["ctest --test-dir build --output-on-failure"],cpp:["ctest --test-dir build --output-on-failure"],elixir:["mix test"],ruby:["rspec","ruby -m minitest"],clojure:["clojure -X:test"],scala:["sbt test"],kotlin:["./gradlew test","gradle test"],deno:["deno task test","deno test"],bun:["bun test","bun run test"],"jvm-generic":["mvn test","gradle test"],unknown:[]},build:{python:["python -m build","python setup.py build"],node:["npm run build"],go:["go build -o app .","go build ./..."],java:["mvn package -DskipTests","gradle build -x test"],php:['echo "PHP build: typically no build step"'],rust:["cargo build --release"],dotnet:["dotnet build -c Release"],c:["cmake --build build"],cpp:["cmake --build build"],elixir:["mix compile"],ruby:["gem build *.gemspec"],clojure:[],scala:["sbt compile"],kotlin:["./gradlew build","gradle build"],deno:["deno task build"],bun:["bun run build"],"jvm-generic":["mvn package -DskipTests","gradle build"],unknown:[]},start:{python:["python app.py","python main.py","uvicorn main:app --reload"],node:["npm start","node index.js","node src/index.js"],go:["./app","go run main.go","go run ./..."],java:["mvn spring-boot:run","gradle bootRun","java -jar target/*.jar"],php:["php -S 0.0.0.0:8000","php artisan serve"],rust:["cargo run --release","./target/release/app"],dotnet:["dotnet run"],c:[],cpp:[],elixir:["mix phx.server","iex -S mix"],ruby:["rails server","ruby app.rb","bundle exec puma"],clojure:["clojure -M:run"],scala:["sbt run"],kotlin:["./gradlew run","gradle run"],deno:["deno task start","deno task dev"],bun:["bun run start","bun run dev"],"jvm-generic":["java -jar *.jar","gradle run"],unknown:[]}};function se(e,r){if(r){let t=r.trim().toLowerCase().replace(/[_.\s]+/g,"-"),n=f$1(r),o=`${e}-${n==="gofiber"?"fiber":n==="gogin"?"gin":n==="dotnet"?"aspnetcore":n!=="unknown"?n:t==="fiber"?"fiber":t==="aspnetcore"||t==="asp-net-core"?"aspnetcore":t}`;return lt[o]}}function Ke(e,r,t){if(r){let n=se(e,r);if(n&&n.commands[t])return n.commands[t]}if(["init","test","build","start"].includes(t)){let n=pt[t]?.[e]??[];return n.length>0?n[0]:void 0}}var mt={test:"test",build:"build",start:"start"};function ye(e){if(e.stage==="init")return e.runtime==="node"?c$1(e.projectPath):Ke(e.runtime,e.framework,e.stage);if(e.runtime==="node"){let r=mt[e.stage];if(r){let t=u$1(e.projectPath,r,{framework:e.framework});if(t)return b$1(e.projectPath,t.scriptName)}}return Ke(e.runtime,e.framework,e.stage)}function ft(e){let r=k(e).map(t=>t==="python"?"python":t==="node"||t==="bun"?"node":t==="go"?"go":t==="java"?"java":t==="php"?"php":t==="rust"?"rust":t==="dotnet"?"dotnet":t==="elixir"?"elixir":t==="ruby"?"ruby":t==="clojure"||t==="scala"||t==="kotlin"?"jvm-generic":null).filter(t=>t!==null).filter((t,n,s)=>s.indexOf(t)===n);return {primary:r.length>0?r[0]:"unknown",secondary:r.slice(1)}}function Ve(e){return ft(e).primary}function he(e,r){if(!e)return "unknown";r||(r={setup:["ModuleNotFoundError","No module named","npm ERR!","error:","not found"],"test-failure":["FAILED","FAIL","failed"],dependency:["cannot find module","import.*error"],runtime:["Exception","Error:","panic","TypeError"],timeout:["timeout","Timeout","deadline exceeded"],unknown:[]});for(let[t,n]of Object.entries(r))for(let s of n)if(new RegExp(s,"i").test(e))return t;return "unknown"}async function ae(e,r){let t=e.split(/[&|;]\s*/)[0].trim().split(/\s+/)[0];if(["echo","cd","pwd","test","true","false","exit"].includes(t))return {valid:true};if(t.includes("/")||t.includes("\\")){let s=f.isAbsolute(t)?t:f.resolve(r??process.cwd(),t);try{return await Y.promises.access(s,process.platform==="win32"?Y.constants.F_OK:Y.constants.X_OK),{valid:true}}catch{return {valid:false,reason:`Command '${t}' not found or not executable in '${r??process.cwd()}'`}}}try{let s=process.platform==="win32"?"where":"which";if((await execa(s,[t],{reject:false})).exitCode===0)return {valid:true}}catch{}return {valid:false,reason:`Command '${t}' not found or not executable`}}function Je(e,r,t){if(!r)return e;let n=typeof r=="object"&&!Array.isArray(r)&&("dev"in r||"staging"in r||"prod"in r||"default"in r)&&!Object.keys(r).some(s=>["init","test","build","start"].includes(s))?r:{};return t&&typeof n[t]=="string"?n[t]:typeof n.default=="string"?n.default:e}async function qe(e,r){if(!e)return {healthy:true};switch(e.type){case "port":{let t=e.value;try{let n=await import('net');return new Promise(s=>{let o=new n.Socket,i=5e3;o.setTimeout(i),o.on("connect",()=>{o.destroy(),s({healthy:true,reason:`Port ${t} is listening`});}),o.on("timeout",()=>{o.destroy(),s({healthy:false,reason:`Port ${t} timeout after ${i}ms`});}),o.on("error",l=>{o.destroy(),s({healthy:false,reason:`Port ${t} error: ${String(l)}`});}),o.connect(t,"localhost");})}catch(n){return {healthy:false,reason:`Port check error: ${n instanceof Error?n.message:String(n)}`}}}case "http":{let t=e.value,n;try{let s=new AbortController;n=setTimeout(()=>s.abort(),5e3);let o=await fetch(t,{method:"GET",signal:s.signal});return {healthy:o.status===200,reason:`HTTP ${o.status}`,metadata:{status:o.status}}}catch(s){return {healthy:false,reason:`HTTP check error: ${s instanceof Error?s.message:String(s)}`}}finally{n&&clearTimeout(n);}}case "log":{let t=e.value;if(!r)return {healthy:true};try{let n=[f.join(r,".workspai","last-run.log"),f.join(r,".rapidkit","last-run.log")].find(s=>Y.existsSync(s));if(n){let s=Y.readFileSync(n,"utf-8"),o=new RegExp(t,"i");return {healthy:o.test(s),reason:o.test(s)?"Log pattern found":"Log pattern not found"}}return {healthy:true,reason:"No log file to check"}}catch(n){return {healthy:false,reason:`Log check error: ${n instanceof Error?n.message:String(n)}`}}}case "command":{let t=e.value;try{let n=await execa(t,[],{cwd:r,reject:false,shell:true});return {healthy:n.exitCode===0,reason:n.exitCode===0?"Health check passed":"Health check failed",metadata:{exitCode:n.exitCode}}}catch(n){return {healthy:false,reason:`Command check error: ${n instanceof Error?n.message:String(n)}`}}}default:return {healthy:true}}}var Ye={init:"init",test:"test",build:"build",start:"start"};function gt(e){return e in Ye?Ye[e]:null}function yt(e,r){let n=q$1(e)?.contextJson?.commands;if(!n||typeof n!="object"||Array.isArray(n))return;let s=n[r];if(typeof s=="string"&&s.trim().length>0)return s.trim();if(s&&typeof s=="object"&&!Array.isArray(s)){let o=s,i=o.default??o.dev;if(typeof i=="string"&&i.trim().length>0)return i.trim()}}function Xe(e,r,t=z(e)){let n=gt(r);if(!n)return yt(e,r)?{supported:true}:{supported:false,reason:`Workspace stage "${r}" is not part of the Workspai fleet contract.`};if(!t.projectRoot)return {supported:false,reason:"No Workspai project metadata was detected for this target."};let s=t.commandMap[n];if(!s||s.status!=="supported"){let o=t.runtimeSupportTier==="observed"||t.frameworkSupportTier==="observed";return {supported:false,reason:s?.reason??`Command "${n}" is not supported for this project runtime/framework.`,shouldFail:!o}}return {supported:true}}var ht=new Set(["init","test","build","start"]),kt=new Set([".git","node_modules",".workspai",".rapidkit",".venv","dist","build","coverage","htmlcov"]);async function V(e){try{return await Y.promises.access(e,Y.constants.F_OK),true}catch{return false}}function Qe(e,r){let t=f.relative(f.resolve(e),f.resolve(r));return t===""||!t.startsWith(`..${f.sep}`)&&t!==".."&&!f.isAbsolute(t)}function bt(e){let r=f.resolve(e.projectPath,e.unit.root);return !e.selectedProjectPaths.some(t=>f.resolve(t)===f.resolve(e.projectPath)?false:Qe(e.projectPath,t)&&Qe(t,r))}async function wt(e){for(let r of e)if(await V(r))return true;return false}async function vt(e,r,t){if(r==="python"){let s=[f.join(e,".workspai","cli.py"),f.join(e,".rapidkit","cli.py")];for(let o of s)if(await V(o))return {valid:true};return {valid:false,reason:"Project-local .workspai/cli.py is missing. Run `workspai init` in this project first."}}let n=t.trim().split(/\s+/)[0];if(n&&["npm","npx","pnpm","yarn"].includes(n)){let s=e$1(n);if((await execa(s.command,[...s.prefixArgs,"--version"],{reject:false,env:g$2()})).exitCode===0)return {valid:true}}return ae(t,e)}async function ie(e){let r=await Y.promises.readFile(e,"utf-8");return JSON.parse(r)}function $(e){return e.replace(/\\/g,"/")}function xt(e){let r=e?.trim();return r?r.startsWith("project:")?r.slice(8).trim()||null:r:null}async function Rt(e){let r=f.join(e,p.model);if(await V(r))try{let n=((await ie(r)).projects??[]).map(s=>typeof s.path=="string"?f.resolve(e,s.path):null).filter(s=>!!s).filter((s,o,i)=>i.indexOf(s)===o).filter(s=>Y.existsSync(s));if(n.length>0)return n.sort()}catch{}return a(e,{skipDirs:kt,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:async(t,n)=>await wt([...u(t,"context.json"),...u(t,"project.json")])?true:f.resolve(t)===f.resolve(n)?false:k(t).length>0})}async function ot(e){for(let r of [f.join(".workspai","project.json"),f.join(".workspai","context.json"),f.join(".rapidkit","project.json"),f.join(".rapidkit","context.json")]){let t=f.join(e,r);if(await V(t))try{let n=await ie(t),s=n.name??n.projectName??n.slug;if(typeof s=="string"&&s.trim())return s.trim()}catch{}}return null}async function St(e,r,t){let n=xt(t);if(!n)return {projects:r,normalizedScope:null};let s=$(n).toLowerCase(),o=[];for(let i of r){let l=$(f.relative(e,i)),g=f.basename(i),y=await ot(i);[l,g,y].filter(c=>typeof c=="string"&&c.length>0).map(c=>$(c).toLowerCase()).includes(s)&&o.push(i);}if(o.length===0)throw new Error(`Workspace run scope did not match any project: ${t}`);return {projects:o,normalizedScope:n}}async function Ct(e,r,t){let n=await execa("git",["diff","--name-only",`${t}...HEAD`],{cwd:e,reject:false,env:a$1()});if(n.exitCode!==0)return new Set(r);let s=n.stdout.split(/\r?\n/).map(i=>i.trim()).filter(i=>i.length>0).map(i=>$(i));if(s.length===0)return new Set;let o=new Set;for(let i of r){let l=$(f.relative(e,i));if(!l||l===".")continue;let g=`${l}/`;s.some(y=>y===l||y.startsWith(g))&&o.add(i);}return o}async function jt(e,r,t$1){let n=await g(e,t.workspaceContract)??q(e,"workspace.contract.json");if(await V(n))try{let u=await Et(e,r,t$1,n);if(u.graphStatus!=="missing")return u}catch{return {expanded:t$1,graphStatus:"invalid",expansionDepth:0}}let s=await g(e,".workspai/workspace-dependency-graph.json")??q(e,"workspace-dependency-graph.json");if(!await V(s))return {expanded:t$1,graphStatus:"missing",expansionDepth:0};let o;try{o=await ie(s);}catch{return {expanded:t$1,graphStatus:"invalid",expansionDepth:0}}let i=new Set(r.map(u=>f.resolve(u))),l=new Map;if(!o||typeof o!="object"||Array.isArray(o))return {expanded:t$1,graphStatus:"invalid",expansionDepth:0};let g$1=Array.isArray(o.projects)?o.projects:[];for(let u of g$1){if(!u||typeof u!="object"||Array.isArray(u))continue;let c=u,d=typeof c.path=="string"?c.path:"",b=f.resolve(e,d);if(!i.has(b))continue;let w=Array.isArray(c.dependsOn)?c.dependsOn.filter(S=>typeof S=="string"):[];for(let S of w){let v=f.resolve(e,S);i.has(v)&&(l.has(v)||l.set(v,new Set),l.get(v)?.add(b));}}let y=d$3(l,t$1);return {expanded:y.reached,graphStatus:"loaded",expansionDepth:y.added}}async function Et(e,r,t,n){let s=await ie(n);if(!s||typeof s!="object"||Array.isArray(s))return {expanded:t,graphStatus:"invalid",expansionDepth:0};let o=s,i=Array.isArray(o.projects)?o.projects:null;if(!i)return {expanded:t,graphStatus:"invalid",expansionDepth:0};let l=new Map,g=new Map;for(let b of r){let w=$(f.relative(e,b));g.set(w,f.resolve(b));}let y=new Map,u=new Map,c=new Map;for(let b of i){if(!b||typeof b!="object"||Array.isArray(b))continue;let w=b,S=typeof w.slug=="string"?w.slug:"",v=typeof w.relativePath=="string"?$(w.relativePath):S,p=g.get(v);!S||!p||l.set(S,p);}for(let b of i){if(!b||typeof b!="object"||Array.isArray(b))continue;let w=b,S=typeof w.slug=="string"?w.slug:"",v=l.get(S);if(!v)continue;let p=w.contracts&&typeof w.contracts=="object"&&!Array.isArray(w.contracts)?w.contracts:{},E=Array.isArray(p.dependsOn)?p.dependsOn.filter(R=>typeof R=="string"):[],N=Array.isArray(p.publishes)?p.publishes.filter(R=>typeof R=="string"):[],G=Array.isArray(p.consumes)?p.consumes.filter(R=>typeof R=="string"):[];for(let R of E){let A=l.get(R);A&&(c.has(A)||c.set(A,new Set),c.get(A)?.add(v));}for(let R of N)y.has(R)||y.set(R,new Set),y.get(R)?.add(v);for(let R of G)u.has(R)||u.set(R,new Set),u.get(R)?.add(v);}for(let[b,w]of y.entries()){let S=u.get(b);if(S)for(let v of w){c.has(v)||c.set(v,new Set);for(let p of S)p!==v&&c.get(v)?.add(p);}}let d=d$3(c,t);return {expanded:d.reached,graphStatus:"loaded",expansionDepth:d.added}}async function Pt(e,r){if(typeof r=="boolean")return r;let t=t$1(e,"policies.yml").find(o=>Y.existsSync(o))??q(e,"policies.yml");if(!await V(t))return true;let n="";try{n=await Y.promises.readFile(t,"utf-8");}catch{return true}let s=n.match(/^[\t ]*rules\.enforce_workspace_run_gates:\s*(true|false)\s*(?:#.*)?$/m);return s?s[1]==="true":true}function At(e,r){let t=process.env.RAPIDKIT_WORKSPACE_RUN_STAGE_TIMEOUT_MS;if(t){let n=Number.parseInt(t,10);if(Number.isFinite(n)&&n>0)return n}return e!=="init"?9e4:r==="python"||r==="java"||r==="jvm-generic"||r==="dotnet"||r==="rust"?6e5:3e5}function Ft(e){let r=e.trim();if(!/^\.\.?[\\/]/.test(r)||/[&|;<>()$`"']/.test(r))return null;let[t,...n]=r.split(/\s+/);return t?{file:t,args:n}:null}function Ze(e,r){let t=Number.parseInt(process.env[e]??"",10);return Number.isFinite(t)&&t>0?t:r}function ke(e){return new Promise(r=>setTimeout(r,e))}async function Ot(e){let r=process.argv[1];if(e.useRapidkitWrapper&&!r)return {exitCode:1,stdout:"",stderr:"Workspai entrypoint is unavailable for startup verification.",healthStatus:{healthy:false,reason:"Workspai entrypoint is unavailable."}};let t=e.useRapidkitWrapper&&r?execa(process.execPath,[r,"start"],{cwd:e.projectPath,reject:false,timeout:e.timeoutMs,env:{...process.env,RAPIDKIT_WORKSPACE_RUN_CHILD:"1"}}):execa(e.finalCommand,[],{cwd:e.projectPath,reject:false,shell:true,timeout:e.timeoutMs}),n=Promise.resolve(t).then(u=>({kind:"exit",result:u}),u=>({kind:"error",error:u})),s=Ze("WORKSPAI_WORKSPACE_RUN_STARTUP_GRACE_MS",2e3),o=await Promise.race([n,ke(s).then(()=>({kind:"alive"}))]);if(o.kind==="error"){let u=typeof o.error=="object"&&o.error!==null&&"timedOut"in o.error&&!!o.error.timedOut;return {exitCode:u?124:1,stdout:"",stderr:o.error instanceof Error?o.error.message:String(o.error),timedOut:u,healthStatus:{healthy:false,reason:"The start command failed before readiness."}}}if(o.kind==="exit"){let u=Number(o.result.exitCode??0);return {exitCode:u,stdout:String(o.result.stdout??""),stderr:String(o.result.stderr??""),healthStatus:{healthy:u===0,reason:u===0?"The start command completed successfully.":`The start command exited with code ${u} before readiness.`}}}let i=se(e.runtime,e.framework)?.healthCheck,l=i?{healthy:false,reason:"The configured health check has not passed yet."}:{healthy:true,reason:`The service remained alive for ${s}ms (bounded startup smoke).`};if(i){let u=Ze("WORKSPAI_WORKSPACE_RUN_STARTUP_HEALTH_TIMEOUT_MS",15e3),c=Date.now()+u;for(;Date.now()<c;){let d=await qe(i,e.projectPath);if(l={healthy:d.healthy,reason:d.reason},d.healthy)break;if((await Promise.race([n,ke(350).then(()=>({kind:"alive"}))])).kind!=="alive"){l={healthy:false,reason:"The service exited before its configured health check passed."};break}}}try{t.kill?.("SIGTERM",{forceKillAfterDelay:1e3});}catch{try{t.kill?.();}catch{}}let g=await Promise.race([n,ke(2e3).then(()=>({kind:"alive"}))]),y=g.kind==="exit"?g.result:void 0;return {exitCode:l.healthy?0:1,stdout:String(y?.stdout??""),stderr:String(y?.stderr??""),healthStatus:l}}async function be(e,r,t,n=false){let s=process.argv[1];if(!s)return {exitCode:1,stdout:"",stderr:"RapidKit entrypoint is unavailable for nested workspace-run execution."};try{let o=execa(process.execPath,[s,...e],{cwd:r,reject:false,timeout:t,forceKillAfterDelay:1e3,env:{...process.env,RAPIDKIT_WORKSPACE_RUN_CHILD:"1"}});n&&(o.stdout?.on("data",l=>process.stdout.write(l)),o.stderr?.on("data",l=>process.stderr.write(l)));let i=await o;return {exitCode:Number(i.exitCode??1),stdout:i.stdout,stderr:i.stderr}}catch(o){return {exitCode:typeof o=="object"&&o!==null&&"timedOut"in o&&!!o.timedOut?124:1,stdout:typeof o=="object"&&o!==null&&"stdout"in o?String(o.stdout??""):"",stderr:typeof o=="object"&&o!==null&&"stderr"in o?String(o.stderr??""):o instanceof Error?o.message:String(o)}}}function Dt(e){return e==="node"||e==="go"||e==="java"||e==="python"||e==="dotnet"||e==="rust"||e==="php"}function Tt(){return process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"}function Wt(e,r=8){if(e.length<=r)return e.join(`
|
|
2
|
+
`);let t=3;return [...e.slice(0,t),...e.slice(-(r-t))].join(`
|
|
3
|
+
`)}function It(e){let r=/(?:\bnot found\b|\bno such\b|\bmissing\b|\bfailed\b|\berror\b|\bexception\b|\bcannot\b|\bdenied\b|\btimeout\b|\btimed out\b|\benoent\b|\beacces\b|\beperm\b)/i;return [...e].reverse().find(t=>r.test(t))??e.at(-1)}async function Mt(e){let r=process.cwd();try{process.chdir(e);let{handleInitCommand:t}=await import('./index.js');return {exitCode:await t(["init"]),stdout:"",stderr:""}}finally{process.chdir(r);}}async function et(e){let r=c=>{let d=g$1(c);return d==="node"||d==="bun"?"node":d==="python"?"python":d==="go"?"go":d==="java"?"java":d==="php"?"php":d==="ruby"?"ruby":d==="rust"?"rust":d==="dotnet"?"dotnet":d==="elixir"?"elixir":d==="clojure"||d==="scala"||d==="kotlin"?"jvm-generic":Ve(e)},t=c=>{if(!c)return;let d=f$1(c);if(new Set(["fastapi","django","flask","nestjs","express","fastify","koa","gofiber","gogin","echo","springboot","laravel","symfony","rails","sinatra","dotnet","actix","axum","rocket","phoenix"]).has(d))return d},n=q$1(e),s=n?.detection??m(e,n?.projectJson??null),o=n?.contextJson,i=r(s.runtime),l=t(s.key),g={},y=new Set(["init","test","build","start"]);if(o?.commands&&typeof o.commands=="object")for(let[c,d]of Object.entries(o.commands))typeof d=="string"&&y.has(c)&&(g[c]=d);let u;if(o?.commandEnvironments&&typeof o.commandEnvironments=="object"){let c=o.commandEnvironments;u={dev:typeof c.dev=="string"?c.dev:void 0,staging:typeof c.staging=="string"?c.staging:void 0,prod:typeof c.prod=="string"?c.prod:void 0,default:typeof c.default=="string"?c.default:void 0};}return {runtime:i,framework:l,commandOverrides:Object.keys(g).length>0?g:void 0,environmentCommandVariants:u,environment:typeof o?.environment=="string"?o.environment:void 0}}async function tt(e,r,t,n,s,o,i,l=false){let g=!s?.[r]&&Dt(t),y;if(s&&s[r]?y=s[r]:g?y=`rapidkit ${r}`:y=ye({projectPath:e,runtime:t,framework:n,stage:r}),!y)return {exitCode:127,command:`<stage not supported for ${t}>`,message:`No stage command found for runtime '${t}' and framework '${n||"unknown"}'`,errorCategory:"runtime"};let u=Je(y,o,i);if(!u)return {exitCode:127,command:y,message:"Failed to resolve stage command",errorCategory:"runtime"};let c=ye({projectPath:e,runtime:t,framework:n,stage:r});if(g){if(c){let x=g?await vt(e,t,c):await ae(c,e);if(!x.valid)return {exitCode:127,command:u,message:x.reason||"Command not available",errorCategory:"setup"}}}else {let x=await ae(u,e);if(!x.valid)return {exitCode:127,command:u,message:x.reason||"Command not available",errorCategory:"setup"}}let d=0,b="",w="",S,v,p=At(r,t),E=Date.now();try{let x=r==="start"?await Ot({projectPath:e,finalCommand:u,useRapidkitWrapper:g,runtime:t,framework:n,timeoutMs:p}):g?r==="init"&&Tt()?await Mt(e):await be([r],e,p,l):await(async()=>{let P=Ft(u);return P?execa(P.file,P.args,{cwd:e,reject:false,timeout:p,forceKillAfterDelay:1e3}):execa(u,[],{cwd:e,reject:false,shell:true,timeout:p,forceKillAfterDelay:1e3})})();if(d=Number(x.exitCode??0),b=x.stdout,w=x.stderr,v=r==="start"?x.healthStatus:void 0,d!==0){let P=`${b}
|
|
4
|
+
${w}`,J=Date.now()-E;S=d===124||he(P)==="timeout"||d===143&&J>=Math.floor(p*.8)?"timeout":he(P);}}catch(x){let P=typeof x=="object"&&x!==null&&"timedOut"in x&&!!x.timedOut;return {exitCode:P?124:1,command:u,message:P?`Stage timed out after ${p}ms`:x instanceof Error?x.message:"Command execution failed",errorCategory:P?"timeout":"runtime"}}let N=`${b}
|
|
5
|
+
${w}`.split(/\r?\n/).map(x=>x.trim()).filter(Boolean),G=Wt(N),R=It(N),A=Date.now()-E,O=d===124||S==="timeout"||d===143&&A>=Math.floor(p*.8),I=d===0?void 0:O?"timeout":S,H=d===0||!I?void 0:{category:I,exitCode:d,command:u,timedOut:O,timeoutMs:p,...G?{outputExcerpt:G}:{}};return {exitCode:d,command:u,errorCategory:I,healthStatus:v,failureDiagnostic:H,message:O?`Stage timed out after ${p}ms`:d!==0?R?`Stage failed with exit code ${d}: ${R}`:`Stage failed with exit code ${d}`:void 0}}function rt(e){try{return JSON.parse(e)}catch{return null}}function $t(e){switch(e){case "dotnet":return "Install .NET 8+ SDK, then rerun `npx workspai setup dotnet` or `npx workspai init`.";case "go":return "Install Go 1.21+, then rerun `npx workspai setup go` or `npx workspai init`.";case "java":case "jvm-generic":return "Install Java 21+ and Maven/Gradle, then rerun `npx workspai setup java` or `npx workspai init`.";case "node":return "Install Node.js LTS and npm/pnpm/yarn, then rerun `npx workspai setup node` or `npx workspai init`.";case "python":return "Install Python 3.10+ and pip/Poetry, then rerun `npx workspai setup python` or `npx workspai init`.";default:return null}}async function Nt(e){let r=[],t=await be(["doctor","workspace","--json"],e);if(t.exitCode!==0)r.push({gate:"doctor-workspace",status:"fail",summary:"doctor workspace command failed"});else {let o=rt(t.stdout)?.healthScore,i=Number(o?.errors??0);Number.isFinite(i)&&i>0?r.push({gate:"doctor-workspace",status:"fail",summary:`doctor workspace reports ${i} error(s)`}):r.push({gate:"doctor-workspace",status:"pass",summary:"doctor workspace passed"});}let n=await be(["readiness","--json"],e);if(n.exitCode!==0)r.push({gate:"readiness",status:"fail",summary:"readiness command failed"});else {let s=rt(n.stdout),o=String(s?.overallStatus??"").toLowerCase();o==="fail"?r.push({gate:"readiness",status:"fail",summary:"readiness overall status is fail"}):o==="warn"?r.push({gate:"readiness",status:"warn",summary:"readiness overall status is warn"}):r.push({gate:"readiness",status:"pass",summary:"readiness overall status is pass"});}return r}var _t=new Set(["dev","stop"]);function Lt(e){let r=e.trim();return !r||_t.has(r.toLowerCase())?false:ht.has(r)?true:/^[a-z][a-z0-9_-]*$/i.test(r)}function nt(e,r,t){let n=$(f.relative(t,r));return (Array.isArray(e.projects)?e.projects:[]).some(o=>{if(!o||typeof o!="object")return false;let i=o,l=[i.relativePath,i.path].filter(g=>typeof g=="string"&&g.length>0).map(g=>$(g));return i.status==="passed"&&(l.includes(n)||l.some(g=>g.endsWith(`/${n}`)))})}function Gt(e,r){return se(e,r)?.dependencies??[]}function Bt(e,r){let t=Math.max(1,Math.min(4,r)),n=Number(e??t);return Number.isFinite(n)?Math.max(1,Math.min(16,Math.trunc(n))):t}async function xr(e$1){if(!Lt(e$1.stage))throw new Error(`Unsupported workspace run stage: ${e$1.stage}`);let r=Date.now(),t=f.resolve(e$1.workspacePath);c({blockId:"workspace.run.resolve",status:"running",message:"Resolving workspace project fleet",component:"workspace-run"});let n=await d(t),s=await Rt(t),{projects:o,normalizedScope:i}=await St(t,s,e$1.scope),l=e$1.affected===true,g=e$1.blastRadius===true,y=e$1.since?.trim()||"HEAD~1",u=l?await Ct(t,o,y):new Set(o),c$1,d$3="not-applicable",b$1=0,w="all";if(l&&g){let m=await jt(t,s,u);c$1=m.expanded,d$3=m.graphStatus,b$1=m.expansionDepth,w="affected+blast-radius";}else l?(c$1=u,w="affected"):(c$1=u,w="all");c({blockId:"workspace.run.resolve",status:"succeeded",message:`Resolved ${o.length} project(s)`,component:"workspace-run",attributes:{projects:o.length,selectionMode:w}}),c({blockId:"workspace.run.gates",status:"running",message:"Evaluating workspace run gates",component:"workspace-run"});let S=e$1.stage==="init"||e$1.planOnly===true?false:await Pt(t,e$1.enforceGates),v=S?await Nt(t):[{gate:"doctor-workspace",status:"skipped",summary:"workspace run gates disabled"},{gate:"readiness",status:"skipped",summary:"workspace run gates disabled"}],p=v.find(m=>m.status==="fail");c({blockId:"workspace.run.gates",status:p?"blocked":"succeeded",message:p?`Blocked by ${p.gate}`:"Workspace run gates passed",component:"workspace-run",attributes:{gates:v}});let E=o.filter(m=>c$1.has(m)),N=e$1.continueOnError===true||e$1.stage==="init",G=e$1.parallel===true,R=Bt(e$1.maxWorkers,E.length),A=E.length,O=0;c({blockId:"workspace.run.execute",status:p?"blocked":"running",message:p?`Execution blocked by ${p.gate}`:`Executing ${e$1.stage} across ${A} project(s)`,component:"workspace-run",progress:{completed:0,total:A},attributes:{stage:e$1.stage,parallel:G,maxWorkers:R}}),e$1.json||console.log(W.gray(`Workspace run (${e$1.stage}) started: ${A} target(s), ${G?`parallel x${R}`:"sequential"}`));let I=new Map;for(let m of s){let h=$(f.relative(t,m)),a=await ot(m),_=o.includes(m),j=_&&c$1.has(m);I.set(m,{path:m,relativePath:h,projectName:a??(f.basename(h)||f.basename(m)),selected:j,affected:j,status:"skipped",exitCode:null,durationMs:0,reason:j?void 0:_?"not affected":"outside scope",framework:void 0,runtimeDetected:void 0,executionCommand:void 0});}if(p)for(let m of E){let h=I.get(m);h&&(h.status="skipped",h.reason=`blocked by ${p.gate}`);}else {let m=async h=>{let a=I.get(h);if(!a)return;let _=$(f.relative(t,h));e$1.json||console.log(W.gray(`\u23F3 [${O}/${A}] ${e$1.stage} ${_}`)),a.selected=true,a.affected=true;let j=Date.now(),M=d$2(h),D=e$1.runtime?.trim().toLowerCase(),B=M.units.filter(k=>bt({projectPath:h,unit:k,selectedProjectPaths:E})).filter(k=>!D||k.runtime===D).map(k=>({unit:k,stage:k.stages.find(F=>F.stage===e$1.stage)})).filter(k=>!!k.stage),X=B.map(({unit:k,stage:F})=>({unitId:k.id,runtime:k.runtime,role:k.role,root:k.root,manifest:k.manifest,stage:F.stage,command:F.command,status:"planned",exitCode:null,durationMs:0}));if(a.runtimeExecutions=X,e$1.planOnly){a.runtimeDetected=B[0]?.unit.runtime,a.status="skipped",a.reason=B.length>0?`plan only: ${B.length} runtime unit(s)`:D?`no ${D} runtime unit supports stage "${e$1.stage}"`:`no runtime unit supports stage "${e$1.stage}"`,a.durationMs=Date.now()-j,O+=1;return}if(M.polyglot||D){if(B.length===0){a.status="failed",a.reason=D?`No ${D} runtime unit supports stage "${e$1.stage}"`:`No runtime unit supports stage "${e$1.stage}"`,a.errorCategory="setup",a.errorMessage=a.reason,a.exitCode=127,a.durationMs=Date.now()-j,O+=1;return}let k;for(let C=0;C<B.length;C+=1){let{unit:xe,stage:Re}=B[C],q=X[C],Se=f.resolve(h,xe.root),dt=Date.now(),pe=await et(Se),U=await tt(Se,e$1.stage,xe.runtime,pe.framework,{[e$1.stage]:Re.command},pe.environmentCommandVariants,pe.environment,!e$1.json);if(q.durationMs=Date.now()-dt,q.exitCode=U.exitCode,q.status=U.exitCode===0?"passed":"failed",q.reason=U.message,q.errorCategory=U.errorCategory,q.failureDiagnostic=U.failureDiagnostic,U.exitCode!==0&&!k&&(k=U.message??Re.command),U.exitCode!==0&&!N){for(let Ce of X.slice(C+1))Ce.status="skipped",Ce.reason="stopped after runtime-unit failure";break}}let F=X.find(C=>C.status==="failed");a.runtimeDetected=B[0]?.unit.runtime,a.executionCommand=X.filter(C=>C.status!=="skipped").map(C=>`[${C.runtime}:${C.root}] ${C.command}`).join(" && "),a.durationMs=Date.now()-j,a.exitCode=F?.exitCode??0,a.status=F?"failed":"passed",a.reason=F?k??"runtime-unit stage failed":void 0,a.errorCategory=F?F.errorCategory??"runtime":void 0,a.errorMessage=a.reason,a.failureDiagnostic=F?.failureDiagnostic,O+=1;return}let{runtime:ce,framework:de,commandOverrides:it,environmentCommandVariants:ut,environment:ct}=await et(h);a.runtimeDetected=ce,a.framework=de;let le=Xe(h,e$1.stage);if(!le.supported){a.status=le.shouldFail===false?"skipped":"failed",a.reason=le.reason??`stage "${e$1.stage}" unsupported for project`,a.durationMs=Date.now()-j,a.exitCode=a.status==="failed"?127:null,a.status==="failed"&&(a.errorCategory="setup",a.errorMessage=a.reason),O+=1;return}if(e$1.reusePassed&&n){let k=n.stages[e$1.stage]??n.stages[e$1.stage];if(k&&nt(k,h,t)){a.status="passed",a.reason="reused passed result from workspace-run-last.json",a.durationMs=Date.now()-j,a.exitCode=0,O+=1,e$1.json||console.log(W.gray(`\u21BA reused passed cache for ${_}`));return}}let ve=Gt(ce,de).filter(k=>k!==e$1.stage);if(ve.length>0&&n){let k=ve.find(F=>{let C=n.stages[F];return !C||!nt(C,h,t)});if(k){a.status="skipped",a.reason=`dependency stage "${k}" not satisfied in workspace-run-last.json`,a.durationMs=Date.now()-j,a.exitCode=null,O+=1;return}}let T=await tt(h,e$1.stage,ce,de,it,ut,ct,!e$1.json);a.executionCommand=T.command,a.errorCategory=T.errorCategory,a.healthStatus=T.healthStatus,a.failureDiagnostic=T.failureDiagnostic,a.durationMs=Date.now()-j,a.exitCode=T.exitCode;let K=a.runtimeExecutions?.[0];if(K&&(K.command=T.command,K.status=T.exitCode===0?"passed":"failed",K.exitCode=T.exitCode,K.durationMs=a.durationMs,K.reason=T.message,K.errorCategory=T.errorCategory,K.failureDiagnostic=T.failureDiagnostic),T.exitCode===0?(a.status="passed",a.reason=void 0):(a.status="failed",a.reason=T.message||"stage command failed",a.errorMessage=T.message),O+=1,!e$1.json){let k=A>0?Math.round(O/A*100):100,F=a.status==="passed"?W.green("\u2705"):W.red("\u274C");if(console.log(W.gray(`${F} [${O}/${A}] (${k}%) ${_} ${a.durationMs}ms`)),a.status==="failed"){a.reason&&console.log(W.red(` Reason: ${a.reason}`)),a.executionCommand&&console.log(W.gray(` Command: ${a.executionCommand}`));let C=$t(a.runtimeDetected);C&&a.errorCategory==="setup"&&console.log(W.gray(` Hint: ${C}`));}}};if(G&&E.length>1){let h=0,a=false,_=new Array(R).fill(null).map(async()=>{for(;h<E.length;){if(a&&!N)return;let j=h;h+=1;let M=E[j];await m(M),I.get(M)?.status==="failed"&&(a=true);}});if(await Promise.all(_),!N&&a){let j=false;for(let M of E){let D=I.get(M);if(D){if(D.status==="failed"){j=true;continue}j&&D.status==="skipped"&&(D.reason=D.reason||"stopped after failure");}}}}else for(let h of E){await m(h);let a=I.get(h);if(!N&&a?.status==="failed"){let _=E.slice(E.indexOf(h)+1);for(let j of _){let M=I.get(j);M&&(M.status="skipped",M.reason="stopped after failure");}break}}}let H=[];for(let m of s){let h=I.get(m);h&&H.push(h);}let x=H.filter(m=>m.status==="passed").length,P=H.filter(m=>m.status==="failed").length,J=H.filter(m=>m.status==="skipped").length;c({blockId:"workspace.run.execute",status:P>0?"failed":p?"blocked":"succeeded",message:`Workspace run finished: ${x} passed, ${P} failed, ${J} skipped`,component:"workspace-run",progress:{completed:A,total:A,percent:100},attributes:{passed:x,failed:P,skipped:J,stage:e$1.stage}});let ue=e$1.strict===true,st=P>0||ue&&v.some(m=>m.status==="fail"||m.status==="warn")?1:0,we={schemaVersion:"1.0",workspacePath:t,stage:e$1.stage,generatedAt:new Date().toISOString(),durationMs:Date.now()-r,options:{affected:l,blastRadius:g,since:l?y:null,parallel:G,maxWorkers:R,continueOnError:N,strict:ue,enforceGates:S,scope:i,reusePassed:e$1.reusePassed===true,planOnly:e$1.planOnly===true,runtime:e$1.runtime?.trim()||null},selection:{mode:w,since:l?y:null,scope:i,graphStatus:d$3,expansionDepth:b$1},gates:{enforced:S,results:v,blocked:!!p,blockingGate:p?.gate},summary:{projectCount:s.length,selectedCount:E.length,passed:x,failed:P,skipped:J,exitCode:st},projects:H,enterpriseControls:{jsonReady:true,evidencePath:b}},at=f.join(t,b);c({blockId:"workspace.run.publish",status:"running",message:"Publishing workspace run evidence",component:"workspace.run"});try{await e(t,we),c({blockId:"workspace.run.publish",status:"succeeded",message:"Workspace run evidence published",component:"workspace.run"}),d$1({workspacePath:t,relativePath:b,blockId:"workspace.run.publish"});}catch(m){throw c({blockId:"workspace.run.publish",status:"failed",message:m instanceof Error?m.message:"Workspace run evidence publish failed",component:"workspace.run"}),m}return e$1.json||(p&&(console.log(W.red(`\u274C Workspace run blocked by ${p.gate}`)),console.log(W.gray(` ${p.summary}`))),console.log(W.cyan(`Workspace run (${e$1.stage}) => passed: ${x}, failed: ${P}, skipped: ${J}`)),console.log(W.gray(`Report: ${at}`))),we}export{At as a,xr as b};
|
|
@@ -1,4 +1,21 @@
|
|
|
1
|
-
import {promises}from'fs';import
|
|
1
|
+
import {promises}from'fs';import c from'path';var n={reviewedAt:"2026-08-31",actions:{checkout:"v7",setupGo:"v7",setupJava:"v6",setupDotnet:"v6",uploadArtifact:"v4",golangciLint:"v9",rustCache:"v2"},go:{version:"1.26",alpine:"3.24",air:"v1.67.4",swag:"v1.16.6",golangciLint:"v2.12.2",fiber:"v2.52.15",fiberSwagger:"v1.3.0",gin:"v1.12.0",ginSwagger:"v1.6.1",swagFiles:"v1.0.1"},springBoot:{java:"21",compatibilityJava:"25",version:"3.5.16",springdoc:"2.9.0",maven:"3.9.9"},dotnet:{targetFramework:"net10.0",sdkChannel:"10.0.x",aspnetPatch:"10.0.11",swashbuckle:"10.2.3",testSdk:"18.9.0",xunit:"2.9.3",xunitRunner:"3.1.5",coverlet:"6.0.4"},rust:{toolchain:"1.98.0",edition:"2024",axum:"0.8.9"}};function m(e){return `version: 2
|
|
2
|
+
updates:
|
|
3
|
+
- package-ecosystem: "${e}"
|
|
4
|
+
directory: "/"
|
|
5
|
+
schedule:
|
|
6
|
+
interval: "weekly"
|
|
7
|
+
open-pull-requests-limit: 5
|
|
8
|
+
groups:
|
|
9
|
+
production-dependencies:
|
|
10
|
+
dependency-type: "production"
|
|
11
|
+
development-dependencies:
|
|
12
|
+
dependency-type: "development"
|
|
13
|
+
- package-ecosystem: "github-actions"
|
|
14
|
+
directory: "/"
|
|
15
|
+
schedule:
|
|
16
|
+
interval: "weekly"
|
|
17
|
+
open-pull-requests-limit: 3
|
|
18
|
+
`}var f=n.go.version,o=`github.com/air-verse/air@${n.go.air}`,i=`github.com/swaggo/swag/cmd/swag@${n.go.swag}`,a="main.go -d cmd/server,internal/handlers,internal/apierr -o docs --parseDependency";function $(e){return e.split(/[-_\s]+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}async function b(e,t){await promises.mkdir(c.dirname(e),{recursive:true}),await promises.writeFile(e,t,"utf8");}function R(e){let t=e.includeLintAndFmt?`
|
|
2
19
|
lint:
|
|
3
20
|
@command -v golangci-lint >/dev/null 2>&1 || (echo "golangci-lint not found. Install: https://golangci-lint.run/usage/install/" && exit 1)
|
|
4
21
|
golangci-lint run ./...
|
|
@@ -18,7 +35,7 @@ GOBIN ?= $(shell go env GOPATH)/bin
|
|
|
18
35
|
|
|
19
36
|
# Hot reload \u2014 installs pinned air version on first use
|
|
20
37
|
dev:
|
|
21
|
-
@test -x "$(GOBIN)/air" || go install ${
|
|
38
|
+
@test -x "$(GOBIN)/air" || go install ${o}
|
|
22
39
|
${e.devCommand}
|
|
23
40
|
|
|
24
41
|
run:
|
|
@@ -52,7 +69,7 @@ docker-up:
|
|
|
52
69
|
|
|
53
70
|
docker-down:
|
|
54
71
|
docker compose down
|
|
55
|
-
`}function
|
|
72
|
+
`}function I(e){return `#!/usr/bin/env sh
|
|
56
73
|
# Workspai ${e.runtimeLabel} project launcher \u2014 generated by Workspai CLI
|
|
57
74
|
# https://workspai.dev
|
|
58
75
|
|
|
@@ -66,7 +83,7 @@ case "$CMD" in
|
|
|
66
83
|
echo "\u{1F439} Initializing ${e.runtimeLabel} project\u2026"
|
|
67
84
|
GOBIN="$(go env GOPATH)/bin"
|
|
68
85
|
echo " \u2192 installing air (hot reload)\u2026"
|
|
69
|
-
go install ${
|
|
86
|
+
go install ${o} 2>/dev/null && echo " \u2713 air" || echo " \u26A0 air install failed (run: go install ${o})"
|
|
70
87
|
echo " \u2192 installing swag (swagger)\u2026"
|
|
71
88
|
go install ${i} 2>/dev/null && echo " \u2713 swag" || echo " \u26A0 swag install failed (run: go install ${i})"
|
|
72
89
|
if [ ! -f ".env" ] && [ -f ".env.example" ]; then
|
|
@@ -134,7 +151,7 @@ case "$CMD" in
|
|
|
134
151
|
exit 1
|
|
135
152
|
;;
|
|
136
153
|
esac
|
|
137
|
-
`}function
|
|
154
|
+
`}function w(e){return `@echo off
|
|
138
155
|
setlocal
|
|
139
156
|
rem Workspai ${e.runtimeLabel} project launcher \u2014 Windows
|
|
140
157
|
set CMD=%1
|
|
@@ -143,7 +160,7 @@ shift
|
|
|
143
160
|
|
|
144
161
|
if "%CMD%"=="init" (
|
|
145
162
|
echo Initializing ${e.runtimeLabel} project...
|
|
146
|
-
go install ${
|
|
163
|
+
go install ${o}
|
|
147
164
|
go install ${i}
|
|
148
165
|
if not exist .env if exist .env.example copy .env.example .env
|
|
149
166
|
go mod tidy
|
|
@@ -202,4 +219,4 @@ echo Available: init, dev, start, build, docs, test, lint, format
|
|
|
202
219
|
echo.
|
|
203
220
|
echo Windows launcher uses native Go commands and does not require GNU Make.
|
|
204
221
|
exit /b 1
|
|
205
|
-
`}export{
|
|
222
|
+
`}export{n as a,m as b,f as c,$ as d,b as e,R as f,I as g,w as h};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {j,m,e}from'./chunk-
|
|
1
|
+
import {j,m,e}from'./chunk-6WOFOOM7.js';import {t}from'./chunk-ODK4LCEL.js';import {u}from'./chunk-VQZ5PI5J.js';import u$1 from'path';import d from'fs-extra';import {parse}from'yaml';import w from'fs';var F=new Set(["backend","desktop","extension","service","frontend","worker","platform","library","infra","docs","test-suite","unknown"]),O=new Set([".git",".workspai","vendor","node_modules","test","tests","testdata","fixtures","samples","examples","third_party"]),I=new Set([...O,".cache",".venv","build","dist","target"]);async function L(e){let n=0,t=async(r,o)=>{if(o>5)return false;let s;try{s=await d.readdir(r,{withFileTypes:true});}catch{return false}for(let c of s.sort((f,l)=>f.name.localeCompare(l.name))){if(c.isFile()&&c.name==="main.go"){let f=await d.readFile(u$1.join(r,c.name),"utf8").catch(()=>"");if(/^\s*package\s+main\b/m.test(f)&&(n+=1,n>1))return true}if(c.isDirectory()&&!O.has(c.name)&&await t(u$1.join(r,c.name),o+1))return true}return false};return t(e,0)}async function M(e,n){if(n!=="c"&&n!=="cpp")return false;let t=new Set,r=async(o,s)=>{if(s>3||t.size>=3)return;let c;try{c=await d.readdir(o,{withFileTypes:true});}catch{return}for(let f of c)if(f.isFile()){let l=f.name.toLowerCase();l==="cmakelists.txt"||l==="meson.build"?t.add("native"):l==="pyproject.toml"||l==="setup.py"?t.add("python"):l==="description"&&u$1.basename(o).toLowerCase()==="r"?t.add("r"):l.endsWith(".gemspec")?t.add("ruby"):l==="pom.xml"||l==="build.gradle"||l==="build.gradle.kts"?t.add("java"):l==="cargo.toml"?t.add("rust"):l==="go.mod"?t.add("go"):l==="package.json"&&t.add("node");}else f.isDirectory()&&!I.has(f.name)&&await r(u$1.join(o,f.name),s+1);};return await r(e,0),t.has("native")&&t.size>=3}async function K(e){if((((await d.readFile(u$1.join(e,"pom.xml"),"utf8").catch(()=>"")).match(/<modules\b[^>]*>([\s\S]*?)<\/modules>/iu)?.[1]??"").match(/<module\b[^>]*>[^<]+<\/module>/giu)??[]).length>=2)return true;for(let r of ["settings.gradle","settings.gradle.kts"]){let o=await d.readFile(u$1.join(e,r),"utf8").catch(()=>"");if(!o)continue;if(new Set([...o.matchAll(/['"](:[^'"]+)['"]/gu)].map(c=>c[1])).size>=2)return true}return false}async function $(e){for(let n of ["compose.yaml","compose.yml","docker-compose.yaml","docker-compose.yml"]){let t=await d.readFile(u$1.join(e,n),"utf8").catch(()=>"");if(t)try{let o=parse(t)?.services??{},s=Object.entries(o).map(([i,p])=>{let g=(()=>{if(typeof p?.build=="string")return `${p.build}|Dockerfile`;if(!p?.build||typeof p.build!="object")return null;let a=p.build.context;if(typeof a!="string"||a.length===0)return null;let j="dockerfile"in p.build&&typeof p.build.dockerfile=="string"?p.build.dockerfile:"Dockerfile";return `${a}|${j}`})();return g?{serviceName:i,service:p,identity:g.replaceAll("\\","/").replace(/\/$/,"")}:null}).filter(i=>i!==null);if(new Set(s.map(i=>i.identity)).size<2)continue;let f=new Set(s.map(i=>i.serviceName)),l=new Set(s.filter(({service:i})=>Array.isArray(i.ports)&&i.ports.length>0).map(({identity:i})=>i)),y=s.some(({service:i})=>(Array.isArray(i.depends_on)?i.depends_on:i.depends_on&&typeof i.depends_on=="object"?Object.keys(i.depends_on):[]).some(g=>typeof g=="string"&&f.has(g)));if(l.size>=2||y)return true}catch{}}return false}async function A(e){try{if(!await d.pathExists(e))return null;let n=await d.readJSON(e);return n&&typeof n=="object"?n:null}catch{return null}}async function z(e){for(let n of e){let t=await A(n);if(t)return t}return null}function C(e){if(typeof e!="string")return null;let n=e.trim().toLowerCase();return F.has(n)?n==="service"?"backend":n:null}function re(e){switch(e){case "backend":case "service":case "worker":return "backend";case "frontend":case "desktop":case "extension":case "library":case "platform":return e;case "infra":return "infrastructure";case "docs":return "documentation";case "test-suite":return "quality";default:return "unknown"}}async function oe(e$1,n,t={}){let r=n??await z(u(e$1,"project.json")),o=j(r)?null:r,s=o===null&&r!==null?m(e$1,null):null,c=C(o?.kind)??C(o?.type);if(c)return c;let f=typeof o?.kit_name=="string"?o.kit_name:typeof o?.kit=="string"?o.kit:t.kit,l=typeof o?.framework=="string"?o.framework:t.framework??s?.key,y=typeof o?.runtime=="string"?o.runtime:t.runtime??s?.runtime,i=`${typeof f=="string"?f:""} ${l??""} ${y??""}`.trim().toLowerCase();if(await $(e$1))return "platform";if(/\b(tauri|electron|wails|desktop)\b/.test(i))return "desktop";if(/\b(vscode-extension|visual studio code extension|jetbrains-plugin|browser-extension)\b/.test(i))return "extension";let p=await d.readFile(u$1.join(e$1,"Cargo.toml"),"utf8").catch(()=>""),g=/^\s*\[workspace\]\s*$/m.test(p)&&!/^\s*\[package\]\s*$/m.test(p),a=await A(u$1.join(e$1,"package.json"));if(a!==null&&(Array.isArray(a.workspaces)||a.workspaces!==null&&typeof a.workspaces=="object")||g||e(e$1))return "platform";if(/\b(frontend|nextjs|next\.js|react|vue|svelte|vite|angular|astro|remix|nuxt)\b/.test(i))return "frontend";if(/\b(fastapi|nestjs|springboot|spring boot|gofiber|gogin|webapi|django|flask|express|fastify|laravel|rails|phoenix|axum|actix|rocket)\b/.test(i))return "backend";if(a){let m={...a.dependencies??{},...a.devDependencies??{}},D=a.scripts??{},b=Object.values(D).filter(k=>typeof k=="string").join(" ").toLowerCase(),_=a.engines??{},N=Array.isArray(a.categories)?a.categories.filter(k=>typeof k=="string"):[];if(m["@tauri-apps/api"]||m["@tauri-apps/cli"]||await d.pathExists(u$1.join(e$1,"src-tauri","tauri.conf.json"))||await d.pathExists(u$1.join(e$1,"src-tauri","tauri.conf.json5"))||m.electron||m["@electron-forge/cli"]||b.includes("electron-forge")||b.includes("electron "))return "desktop";if(typeof _.vscode=="string"||N.some(k=>k.toLowerCase()==="extension packs")||a.publisher&&(a.activationEvents||a.contributes))return "extension";if(m.next||m.react||m.vue||m.svelte||m.vite||m["@angular/core"]||b.includes("next ")||b.includes("vite "))return "frontend";if(a.private===true&&!m.express&&!m["@nestjs/core"])return "library"}return g||await K(e$1)||await d.pathExists(u$1.join(e$1,"go.work"))||await d.pathExists(u$1.join(e$1,"go.mod"))&&await L(e$1)?"platform":await M(e$1,y)?"library":await d.pathExists(u$1.join(e$1,"compose.yaml"))||await d.pathExists(u$1.join(e$1,"compose.yml"))||await d.pathExists(u$1.join(e$1,"docker-compose.yml"))||await d.pathExists(u$1.join(e$1,"docker-compose.yaml"))||await d.pathExists(u$1.join(e$1,"terraform.tf"))?"infra":"backend"}var B={ci:[".github/workflows",".gitlab-ci.yml",".circleci/config.yml","azure-pipelines.yml","bitbucket-pipelines.yml","cloudbuild.yaml","Jenkinsfile",".buildkite/pipeline.yml","prow"],release:[".changeset",".releaserc",".releaserc.json","release.config.js",".goreleaser.yml",".goreleaser.yaml","RELEASING.md","RELEASE.md","tools/release","scripts/release","docs/release","doc/release","build/release.sh","hack/lib/release.sh"],ownership:[".github/CODEOWNERS",".gitlab/CODEOWNERS","CODEOWNERS","docs/CODEOWNERS","OWNERS","OWNERS_ALIASES","MAINTAINERS"]},J=/(?:^|[-_.])(?:release|publish|publishing|distribution)(?:[-_.]|$)/i,V={ci:/\b(?:prow|buildkite|jenkins|teamcity|travis|external ci|test-infra)\b/i,release:/\b(?:release automation|release engineering|release infrastructure|external release)\b/i,ownership:/\b(?:external ownership|central owners|maintainer team|code owners)\b/i};async function U(e,n){let t=[];for(let r of n)try{await w.promises.access(u$1.join(e,r),w.constants.F_OK),t.push(r);}catch{}return t}async function Y(e,n){let t=["README.md","CONTRIBUTING.md","DEVELOPMENT.md","docs/devel/README.md"],r=[];for(let o of t)try{let s=u$1.join(e,o),c=await w.promises.stat(s);if(!c.isFile()||c.size>1024*1024)continue;let f=await w.promises.readFile(s,"utf8");n.test(f)&&r.push(o);}catch{}return r}async function q(e){let n=u$1.join(e,".github","workflows");try{return (await w.promises.readdir(n,{withFileTypes:true})).filter(r=>r.isFile()&&/\.(?:ya?ml)$/i.test(r.name)&&J.test(r.name)).map(r=>`.github/workflows/${r.name}`).sort()}catch{return []}}function H(e,n){let t$1=e?.[n];return t$1?.mode?{status:t$1.mode==="external"?"external-declared":"repository",provider:t$1.provider?.trim()||null,evidence:[t.workspaceContract],reference:t$1.reference?.trim()||null}:null}async function v(e,n,t){let r=H(n,t);if(r)return r;let o=[...await U(e,B[t]),...t==="release"?await q(e):[]];if(o.length>0)return {status:"repository",provider:null,evidence:o,reference:null};let s=await Y(e,V[t]);return s.length>0?{status:"external-observed",provider:null,evidence:s,reference:null}:{status:"unknown",provider:null,evidence:[],reference:null}}async function ue(e){let[n,t,r]=await Promise.all([v(e.projectPath,e.declaration,"ci"),v(e.projectPath,e.declaration,"release"),v(e.projectPath,e.declaration,"ownership")]);return {schemaVersion:"workspai.project-governance.v1",ci:n,release:t,ownership:r}}export{re as a,oe as b,ue as c};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {b as b$1}from'./chunk-COICGD62.js';import {b}from'./chunk-AGZWDYMF.js';import {q as q$1,f,g}from'./chunk-IHKG5C6G.js';import {d}from'./chunk-PTSEDZIV.js';import {h,g as g$1}from'./chunk-FE5R6EUV.js';import {q,p}from'./chunk-ODK4LCEL.js';import E from'path';import A from'fs-extra';var re=q.agentContext,se=p.agentContext;function ne(e){if(typeof e!="string"||!e.trim()||e==="true")return "generic";let t=e.trim().toLowerCase();return t==="codex"||t==="claude"||t==="cursor"||t==="gemini"||t==="qwen"||t==="kimi"||t==="grok"||t==="copilot"||t==="windsurf"||t==="amazon-q"||t==="orca"?t:"generic"}function G(e){return `npx --yes --package workspai workspai ${e}`.trim()}function x(e){return `npx workspai ${e}`.trim()}async function C(e,t,i){let s=E.join(e,t);if(!await A.pathExists(s))return null;try{let n=await A.readJson(s);return typeof n!="object"||n===null||!("schemaVersion"in n)||n.schemaVersion!==i?null:n}catch{return null}}function m(e){return {id:e.id,scope:e.scope,display:x(e.args),execute:G(e.args),description:e.description,...e.project?{project:e.project}:{},freshness:f({id:`command.${e.id}`,label:`${e.id} command`,scope:"command",value:{display:x(e.args),execute:G(e.args)},...e.project?{project:e.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:e.generatedAt,now:e.now,sourceArtifact:p.model,sourcePath:`safeCommands.${e.id}`,reason:"Safe command surfaces are derived from workspace model command capabilities."}}).freshness}}function L(e,t){return `workspace run ${t} --scope project:${e.name}`}function ae(e){return (e.startsWith("project:")?e.slice(8):e).trim().toLowerCase()}function oe(e){return [e.name,e.path,E.basename(e.path),e.absolutePath].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim().toLowerCase())}function ie(e,t,i){let s={generatedAt:e.generatedAt,now:i},n=[m({id:"workspace.model",scope:"workspace",args:"workspace model --json",description:"Read the canonical workspace intelligence model.",...s}),m({id:"workspace.graph.entities",scope:"workspace",args:"workspace graph entities --json",description:"Query proof-backed workspace entities without loading the full graph.",...s}),m({id:"workspace.graph.evidence",scope:"workspace",args:"workspace graph evidence <entity-or-relation> --json",description:"Resolve portable evidence for a graph entity or relation.",...s}),m({id:"workspace.graph.path",scope:"workspace",args:"workspace graph path <from> <to> --json",description:"Find a shortest proof-carrying path between workspace entities.",...s}),m({id:"workspace.doctor",scope:"workspace",args:"doctor workspace --json",description:"Check workspace health before claiming verification.",...s}),m({id:"workspace.pipeline",scope:"workspace",args:"pipeline --json",description:"Run the governed sync, doctor, analyze, readiness, and autopilot loop.",...s}),m({id:"workspace.contract.verify",scope:"workspace",args:"workspace contract verify --json",description:"Verify workspace contract and dependency edges.",...s}),m({id:"workspace.verify",scope:"workspace",args:"workspace verify --json",description:"Evaluate evidence freshness and verification gates before release decisions.",...s})],c=t?[t]:e.projects;for(let a of c)a.commands.fleetStages.includes("test")&&n.push(m({id:`project.${a.name}.test`,scope:"project",project:a.name,args:L(a,"test"),description:`Run tests for ${a.name} through workspace orchestration.`,...s})),a.commands.fleetStages.includes("build")&&n.push(m({id:`project.${a.name}.build`,scope:"project",project:a.name,args:L(a,"build"),description:`Build ${a.name} through workspace orchestration.`,...s}));return n}function ce(e){return e.commands.fleetStages.filter(t=>t==="test"||t==="build").map(t=>`workspace run ${t}`)}function pe(e,t){if(!t?.startsWith("project:"))return;let i=ae(t);if(i)return e.projects.find(s=>oe(s).includes(i))}function de(e,t,i){let s=[...e.validation?.issues??[]];t?.startsWith("project:")&&!i&&s.push({severity:"error",code:"context.scope.project.missing",message:`Requested project scope was not found: ${t}`,target:t});let n=s.filter(a=>a.severity==="error").length,c=s.filter(a=>a.severity==="warning").length;return {status:n>0?"failed":c>0?"warning":"passed",errors:n,warnings:c,issues:s}}async function me(e,t){let i=[],s=[];for(let[n,c]of Object.entries(e.evidence))c&&await g$1(t,c.path)!==null?i.push(`${n}: ${c.path}`):s.push(n);return {available:i.sort(),missing:s.sort()}}function le(e){let t=e.summary.projectCount,i=e.summary.runtimes.length?`${e.summary.runtimes.join(", ")} runtime coverage`:"no runtime coverage",s=e.identity.surfaces.length?e.identity.surfaces.join(", "):"no detected surfaces";return `${e.workspace.name} is a ${e.identity.workspaceType} with ${t} project${t===1?"":"s"}, ${i}, and ${s}.`}function ge(e){let t=["Do not claim a command passed unless a report or command output proves it.","Do not infer secrets or environment values from file names.","Do not change project scope without checking the selected project."];return e.contracts.exists||t.push("Workspace contract is missing; dependency and API edges may be incomplete."),((e.summary.extendedProjects??0)>0||e.summary.observedProjects>0)&&t.push("Some projects use extended or observed support tiers; command coverage may be partial."),t}async function We(e){let t=e.model??await q$1({workspacePath:e.workspacePath,includeEvidence:e.includeEvidence===true,observableScanDepth:e.observableScanDepth,now:e.now}),i=ne(e.agent),s=pe(t,e.scope),n=de(t,e.scope,s);if(e.strict===true&&n.status!=="passed"){let r=n.issues.map(g=>`${g.severity}:${g.code}:${g.target}`).join(", ");throw new Error(`Workspace context strict validation failed: ${r}`)}let c=e.now??new Date,a=t.facts??[],K=new Set((s?[s]:t.projects).map(r=>r.name)),R=a.filter(r=>r.project?K.has(r.project):true),H=(s?[s]:t.projects).map(r=>{let g=R.filter(p=>p.project===r.name);return {name:r.name,path:r.path,kind:r.kind,category:r.category,runtime:r.runtime,framework:r.frameworkDisplayName,...r.generator?{generator:r.generator}:{},createCapability:r.createCapability,supportTier:r.supportTier,...r.governance?{governance:r.governance}:{},safeCommands:ce(r),importantFiles:r.importantFiles,facts:g}}),S=await me(t,e.workspacePath),F=E.join(e.workspacePath,p.knowledgeGraph),u=await A.pathExists(F)?await A.readJson(F).catch(()=>null):null,N=false;if(u?.schemaVersion===q.knowledgeGraph)try{b(u,t),N=true;}catch{}let $=le(t),M=ie(t,s,c),b$2=await C(e.workspacePath,p.impact,q.impact),l=await C(e.workspacePath,p.doctor,q.doctor),v=await C(e.workspacePath,p.analyze,q.analyze),k=await C(e.workspacePath,p.readiness,q.readiness),h=await C(e.workspacePath,p.verify,q.verify),w=await C(e.workspacePath,p.explain,q.explain),f$1=await C(e.workspacePath,p.diff,q.diff),B=b$2?.summary?{changed:b$2.summary.changed,risk:b$2.summary.risk,affectedProjects:b$2.summary.affectedProjects,blastRadius:b$2.summary.blastRadius,recommendedCommands:b$2.summary.recommendedCommands}:void 0,U=l?.summary?{verdict:l.summary.verdict,totalIssues:l.summary.totalIssues,advisoryFindings:l.summary.advisoryFindings,blockingFindings:l.summary.blockingFindings,unknownFindings:l.summary.unknownFindings,hasSystemErrors:l.summary.hasSystemErrors,topSignals:(()=>{let r=Array.isArray(l.projects)?l.projects:[],g=[];for(let p of r.slice(0,6)){let te=Array.isArray(p.probes)?p.probes:[];for(let y of te.slice(0,10))(y?.status==="fail"||y?.severity==="error")&&g.push({label:y.label,scope:y.scope,issueClass:y.issueClass,status:y.status,severity:y.severity,recommendation:y.recommendation});}return g.slice(0,8)})()}:void 0,J=v?.summary?{score:v.summary.score,verdict:v.summary.verdict,findingCounts:v.summary.findings,topFindings:(Array.isArray(v.findings)?v.findings:[]).filter(p=>p?.severity==="fail"||p?.severity==="warn").slice(0,8).map(p=>({severity:p.severity,title:p.title,target:p.target,remediation:p.remediation}))}:void 0,X=k?{overallStatus:k.overallStatus,blocking:k.blocking,blockingReasons:k.blockingReasons,evidencePath:k.evidencePath,gates:Array.isArray(k.gates)?k.gates.slice(0,6).map(r=>({gate:r.gate,status:r.status,summary:r.summary})):void 0}:void 0,Q=h?.summary?{verdict:h.summary.verdict,exitCode:h.summary.exitCode,stepsFailed:h.summary.stepsFailed,stepsMissing:h.summary.stepsMissing,blockingReasons:h.blockingReasons,missingEvidence:h.missingEvidence}:void 0,Y=w?{summary:w.summary,blockingReasons:w.blockingReasons,releaseVerdict:w.releaseVerdict,evidenceFreshness:w.evidenceFreshness,sections:Array.isArray(w.sections)?w.sections.slice(0,4).map(r=>({id:r.id,title:r.title,body:r.body})):void 0}:void 0,Z=f$1?.summary?{changed:f$1.summary.changed,addedProjects:f$1.summary.addedProjects,removedProjects:f$1.summary.removedProjects,changedProjects:f$1.summary.changedProjects,workspaceChanges:f$1.summary.workspaceChanges,validationChanges:f$1.summary.validationChanges,gitChangedFiles:f$1.summary.gitChangedFiles}:void 0,ee=M.map(r=>f({id:`context.command.${r.id}`,label:`${r.id} safe command`,scope:"command",value:{display:r.display,execute:r.execute,scope:r.scope},...r.project?{project:r.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:t.generatedAt,now:c,sourceArtifact:p.agentContext,sourcePath:`safeCommands.${r.id}`,reason:"Context safe commands are derived from workspace model command capabilities."}})),I=[...R,...ee],W=g({facts:I,generatedAt:c.toISOString(),now:c}),j=b$1();return {schemaVersion:re,generatedAt:c.toISOString(),agent:i,workspaceSummary:$,modelRef:p.model,knowledgeGraph:{artifact:p.knowledgeGraph,schemaVersion:q.knowledgeGraph,available:N,...typeof u?.quality?.entityCount=="number"?{entityCount:u.quality.entityCount}:{},...typeof u?.quality?.relationCount=="number"?{relationCount:u.quality.relationCount}:{},...typeof u?.quality?.proofCount=="number"?{proofCount:u.quality.proofCount}:{},queryCommands:[x("workspace graph search <query> --limit 12 --json"),x("workspace graph entities [kind] --json"),x("workspace graph evidence <entity-or-relation> --json"),x("workspace graph path <from> <to> --json")]},intelligenceChain:{schemaVersion:j.schemaVersion,contractPath:j.contractPath,currentStep:"context",canonicalReadOrder:[...j.consumers.agents.canonicalReadOrder]},workspace:{name:t.workspace.name,root:`workspace:${t.workspace.name}`,type:t.identity.workspaceType,...t.workspace.profile?{profile:t.workspace.profile}:{}},scope:{requested:e.scope??"workspace",...s?{activeProject:s.name}:{}},projects:H,safeCommands:M,facts:I,factFreshness:W,evidence:S,policies:{mode:t.policies.mode,source:t.policies.source},contracts:{exists:t.contracts.exists,path:t.contracts.workspaceContractPath},validation:n,agentInstructions:[`Read \`${p.agentIndex}\` first, then this context pack and linked evidence reports.`,"Use `workspace graph search <query> --limit 12 --json` for bounded, proof-backed retrieval before loading the full graph.",`Load \`${p.knowledgeGraph}\` only when a complete graph export is explicitly required.`,"Use this context as the workspace source of truth before inspecting random files.","Prefer workspace-level evidence over generic framework assumptions.","Use `display` commands when explaining steps to a human.","Use `execute` commands when launching commands from automation or tooling.","Treat `facts[].freshness.verifyBeforeUse` as a hard refresh requirement before using that fact in advice, fixes, or release decisions.","Do not carry extracted facts beyond their freshness contract; re-read or regenerate evidence when the contract says stale, unknown, live, or verify-before-use.","Keep project-scoped advice tied to the active project scope.","Regenerate stale grounding with `npx workspai workspace agent-sync --write --refresh-context`."],unsafeAssumptions:[...ge(t),...W.verifyBeforeUseFacts>0?[`${W.verifyBeforeUseFacts} fact(s) require verification before use; do not treat them as durable workspace structure.`]:[]],humanSummary:[$,`Evidence available: ${S.available.length}. Missing evidence groups: ${S.missing.join(", ")||"none"}.`,s?`Active project scope: ${s.name} (${s.frameworkDisplayName}).`:"Scope: whole workspace."].join(`
|
|
1
|
+
import {b as b$1}from'./chunk-COICGD62.js';import {b}from'./chunk-QYXX6G5O.js';import {q as q$1,f,g}from'./chunk-BVWDG66W.js';import {d}from'./chunk-WPZUKU2B.js';import {h,g as g$1}from'./chunk-FE5R6EUV.js';import {q,p}from'./chunk-ODK4LCEL.js';import E from'path';import A from'fs-extra';var re=q.agentContext,se=p.agentContext;function ne(e){if(typeof e!="string"||!e.trim()||e==="true")return "generic";let t=e.trim().toLowerCase();return t==="codex"||t==="claude"||t==="cursor"||t==="gemini"||t==="qwen"||t==="kimi"||t==="grok"||t==="copilot"||t==="windsurf"||t==="amazon-q"||t==="orca"?t:"generic"}function G(e){return `npx --yes --package workspai workspai ${e}`.trim()}function x(e){return `npx workspai ${e}`.trim()}async function C(e,t,i){let s=E.join(e,t);if(!await A.pathExists(s))return null;try{let n=await A.readJson(s);return typeof n!="object"||n===null||!("schemaVersion"in n)||n.schemaVersion!==i?null:n}catch{return null}}function m(e){return {id:e.id,scope:e.scope,display:x(e.args),execute:G(e.args),description:e.description,...e.project?{project:e.project}:{},freshness:f({id:`command.${e.id}`,label:`${e.id} command`,scope:"command",value:{display:x(e.args),execute:G(e.args)},...e.project?{project:e.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:e.generatedAt,now:e.now,sourceArtifact:p.model,sourcePath:`safeCommands.${e.id}`,reason:"Safe command surfaces are derived from workspace model command capabilities."}}).freshness}}function L(e,t){return `workspace run ${t} --scope project:${e.name}`}function ae(e){return (e.startsWith("project:")?e.slice(8):e).trim().toLowerCase()}function oe(e){return [e.name,e.path,E.basename(e.path),e.absolutePath].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim().toLowerCase())}function ie(e,t,i){let s={generatedAt:e.generatedAt,now:i},n=[m({id:"workspace.model",scope:"workspace",args:"workspace model --json",description:"Read the canonical workspace intelligence model.",...s}),m({id:"workspace.graph.entities",scope:"workspace",args:"workspace graph entities --json",description:"Query proof-backed workspace entities without loading the full graph.",...s}),m({id:"workspace.graph.evidence",scope:"workspace",args:"workspace graph evidence <entity-or-relation> --json",description:"Resolve portable evidence for a graph entity or relation.",...s}),m({id:"workspace.graph.path",scope:"workspace",args:"workspace graph path <from> <to> --json",description:"Find a shortest proof-carrying path between workspace entities.",...s}),m({id:"workspace.doctor",scope:"workspace",args:"doctor workspace --json",description:"Check workspace health before claiming verification.",...s}),m({id:"workspace.pipeline",scope:"workspace",args:"pipeline --json",description:"Run the governed sync, doctor, analyze, readiness, and autopilot loop.",...s}),m({id:"workspace.contract.verify",scope:"workspace",args:"workspace contract verify --json",description:"Verify workspace contract and dependency edges.",...s}),m({id:"workspace.verify",scope:"workspace",args:"workspace verify --json",description:"Evaluate evidence freshness and verification gates before release decisions.",...s})],c=t?[t]:e.projects;for(let a of c)a.commands.fleetStages.includes("test")&&n.push(m({id:`project.${a.name}.test`,scope:"project",project:a.name,args:L(a,"test"),description:`Run tests for ${a.name} through workspace orchestration.`,...s})),a.commands.fleetStages.includes("build")&&n.push(m({id:`project.${a.name}.build`,scope:"project",project:a.name,args:L(a,"build"),description:`Build ${a.name} through workspace orchestration.`,...s}));return n}function ce(e){return e.commands.fleetStages.filter(t=>t==="test"||t==="build").map(t=>`workspace run ${t}`)}function pe(e,t){if(!t?.startsWith("project:"))return;let i=ae(t);if(i)return e.projects.find(s=>oe(s).includes(i))}function de(e,t,i){let s=[...e.validation?.issues??[]];t?.startsWith("project:")&&!i&&s.push({severity:"error",code:"context.scope.project.missing",message:`Requested project scope was not found: ${t}`,target:t});let n=s.filter(a=>a.severity==="error").length,c=s.filter(a=>a.severity==="warning").length;return {status:n>0?"failed":c>0?"warning":"passed",errors:n,warnings:c,issues:s}}async function me(e,t){let i=[],s=[];for(let[n,c]of Object.entries(e.evidence))c&&await g$1(t,c.path)!==null?i.push(`${n}: ${c.path}`):s.push(n);return {available:i.sort(),missing:s.sort()}}function le(e){let t=e.summary.projectCount,i=e.summary.runtimes.length?`${e.summary.runtimes.join(", ")} runtime coverage`:"no runtime coverage",s=e.identity.surfaces.length?e.identity.surfaces.join(", "):"no detected surfaces";return `${e.workspace.name} is a ${e.identity.workspaceType} with ${t} project${t===1?"":"s"}, ${i}, and ${s}.`}function ge(e){let t=["Do not claim a command passed unless a report or command output proves it.","Do not infer secrets or environment values from file names.","Do not change project scope without checking the selected project."];return e.contracts.exists||t.push("Workspace contract is missing; dependency and API edges may be incomplete."),((e.summary.extendedProjects??0)>0||e.summary.observedProjects>0)&&t.push("Some projects use extended or observed support tiers; command coverage may be partial."),t}async function We(e){let t=e.model??await q$1({workspacePath:e.workspacePath,includeEvidence:e.includeEvidence===true,observableScanDepth:e.observableScanDepth,now:e.now}),i=ne(e.agent),s=pe(t,e.scope),n=de(t,e.scope,s);if(e.strict===true&&n.status!=="passed"){let r=n.issues.map(g=>`${g.severity}:${g.code}:${g.target}`).join(", ");throw new Error(`Workspace context strict validation failed: ${r}`)}let c=e.now??new Date,a=t.facts??[],K=new Set((s?[s]:t.projects).map(r=>r.name)),R=a.filter(r=>r.project?K.has(r.project):true),H=(s?[s]:t.projects).map(r=>{let g=R.filter(p=>p.project===r.name);return {name:r.name,path:r.path,kind:r.kind,category:r.category,runtime:r.runtime,framework:r.frameworkDisplayName,...r.generator?{generator:r.generator}:{},createCapability:r.createCapability,supportTier:r.supportTier,...r.governance?{governance:r.governance}:{},safeCommands:ce(r),importantFiles:r.importantFiles,facts:g}}),S=await me(t,e.workspacePath),F=E.join(e.workspacePath,p.knowledgeGraph),u=await A.pathExists(F)?await A.readJson(F).catch(()=>null):null,N=false;if(u?.schemaVersion===q.knowledgeGraph)try{b(u,t),N=true;}catch{}let $=le(t),M=ie(t,s,c),b$2=await C(e.workspacePath,p.impact,q.impact),l=await C(e.workspacePath,p.doctor,q.doctor),v=await C(e.workspacePath,p.analyze,q.analyze),k=await C(e.workspacePath,p.readiness,q.readiness),h=await C(e.workspacePath,p.verify,q.verify),w=await C(e.workspacePath,p.explain,q.explain),f$1=await C(e.workspacePath,p.diff,q.diff),B=b$2?.summary?{changed:b$2.summary.changed,risk:b$2.summary.risk,affectedProjects:b$2.summary.affectedProjects,blastRadius:b$2.summary.blastRadius,recommendedCommands:b$2.summary.recommendedCommands}:void 0,U=l?.summary?{verdict:l.summary.verdict,totalIssues:l.summary.totalIssues,advisoryFindings:l.summary.advisoryFindings,blockingFindings:l.summary.blockingFindings,unknownFindings:l.summary.unknownFindings,hasSystemErrors:l.summary.hasSystemErrors,topSignals:(()=>{let r=Array.isArray(l.projects)?l.projects:[],g=[];for(let p of r.slice(0,6)){let te=Array.isArray(p.probes)?p.probes:[];for(let y of te.slice(0,10))(y?.status==="fail"||y?.severity==="error")&&g.push({label:y.label,scope:y.scope,issueClass:y.issueClass,status:y.status,severity:y.severity,recommendation:y.recommendation});}return g.slice(0,8)})()}:void 0,J=v?.summary?{score:v.summary.score,verdict:v.summary.verdict,findingCounts:v.summary.findings,topFindings:(Array.isArray(v.findings)?v.findings:[]).filter(p=>p?.severity==="fail"||p?.severity==="warn").slice(0,8).map(p=>({severity:p.severity,title:p.title,target:p.target,remediation:p.remediation}))}:void 0,X=k?{overallStatus:k.overallStatus,blocking:k.blocking,blockingReasons:k.blockingReasons,evidencePath:k.evidencePath,gates:Array.isArray(k.gates)?k.gates.slice(0,6).map(r=>({gate:r.gate,status:r.status,summary:r.summary})):void 0}:void 0,Q=h?.summary?{verdict:h.summary.verdict,exitCode:h.summary.exitCode,stepsFailed:h.summary.stepsFailed,stepsMissing:h.summary.stepsMissing,blockingReasons:h.blockingReasons,missingEvidence:h.missingEvidence}:void 0,Y=w?{summary:w.summary,blockingReasons:w.blockingReasons,releaseVerdict:w.releaseVerdict,evidenceFreshness:w.evidenceFreshness,sections:Array.isArray(w.sections)?w.sections.slice(0,4).map(r=>({id:r.id,title:r.title,body:r.body})):void 0}:void 0,Z=f$1?.summary?{changed:f$1.summary.changed,addedProjects:f$1.summary.addedProjects,removedProjects:f$1.summary.removedProjects,changedProjects:f$1.summary.changedProjects,workspaceChanges:f$1.summary.workspaceChanges,validationChanges:f$1.summary.validationChanges,gitChangedFiles:f$1.summary.gitChangedFiles}:void 0,ee=M.map(r=>f({id:`context.command.${r.id}`,label:`${r.id} safe command`,scope:"command",value:{display:r.display,execute:r.execute,scope:r.scope},...r.project?{project:r.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:t.generatedAt,now:c,sourceArtifact:p.agentContext,sourcePath:`safeCommands.${r.id}`,reason:"Context safe commands are derived from workspace model command capabilities."}})),I=[...R,...ee],W=g({facts:I,generatedAt:c.toISOString(),now:c}),j=b$1();return {schemaVersion:re,generatedAt:c.toISOString(),agent:i,workspaceSummary:$,modelRef:p.model,knowledgeGraph:{artifact:p.knowledgeGraph,schemaVersion:q.knowledgeGraph,available:N,...typeof u?.quality?.entityCount=="number"?{entityCount:u.quality.entityCount}:{},...typeof u?.quality?.relationCount=="number"?{relationCount:u.quality.relationCount}:{},...typeof u?.quality?.proofCount=="number"?{proofCount:u.quality.proofCount}:{},queryCommands:[x("workspace graph search <query> --limit 12 --json"),x("workspace graph entities [kind] --json"),x("workspace graph evidence <entity-or-relation> --json"),x("workspace graph path <from> <to> --json")]},intelligenceChain:{schemaVersion:j.schemaVersion,contractPath:j.contractPath,currentStep:"context",canonicalReadOrder:[...j.consumers.agents.canonicalReadOrder]},workspace:{name:t.workspace.name,root:`workspace:${t.workspace.name}`,type:t.identity.workspaceType,...t.workspace.profile?{profile:t.workspace.profile}:{}},scope:{requested:e.scope??"workspace",...s?{activeProject:s.name}:{}},projects:H,safeCommands:M,facts:I,factFreshness:W,evidence:S,policies:{mode:t.policies.mode,source:t.policies.source},contracts:{exists:t.contracts.exists,path:t.contracts.workspaceContractPath},validation:n,agentInstructions:[`Read \`${p.agentIndex}\` first, then this context pack and linked evidence reports.`,"Use `workspace graph search <query> --limit 12 --json` for bounded, proof-backed retrieval before loading the full graph.",`Load \`${p.knowledgeGraph}\` only when a complete graph export is explicitly required.`,"Use this context as the workspace source of truth before inspecting random files.","Prefer workspace-level evidence over generic framework assumptions.","Use `display` commands when explaining steps to a human.","Use `execute` commands when launching commands from automation or tooling.","Treat `facts[].freshness.verifyBeforeUse` as a hard refresh requirement before using that fact in advice, fixes, or release decisions.","Do not carry extracted facts beyond their freshness contract; re-read or regenerate evidence when the contract says stale, unknown, live, or verify-before-use.","Keep project-scoped advice tied to the active project scope.","Regenerate stale grounding with `npx workspai workspace agent-sync --write --refresh-context`."],unsafeAssumptions:[...ge(t),...W.verifyBeforeUseFacts>0?[`${W.verifyBeforeUseFacts} fact(s) require verification before use; do not treat them as durable workspace structure.`]:[]],humanSummary:[$,`Evidence available: ${S.available.length}. Missing evidence groups: ${S.missing.join(", ")||"none"}.`,s?`Active project scope: ${s.name} (${s.frameworkDisplayName}).`:"Scope: whole workspace."].join(`
|
|
2
2
|
`),impactSummary:B,doctorSummary:U,analyzeSummary:J,readinessSummary:X,verifySummary:Q,explainSummary:Y,diffSummary:Z}}async function je(e,t){return h(t,se,d(e))}export{re as a,se as b,We as c,je as d};
|